如何從 MongoDB 中的嵌入陣列獲取特定元素?
要獲取特定元素,請使用帶點表示法的 $ 匹配。我們建立一個包含文件的集合 -
> db.demo641.insert(
... {
... ProductId:101,
... "ProductInformation":
... ( [
... {
... ProductName:"Product-1",
... "ProductPrice":1000
... },
... {
... ProductName:"Product-2",
... "ProductPrice":500
... },
... {
... ProductName:"Product-3",
... "ProductPrice":2000
... },
... {
... ProductName:"Product-4",
... "ProductPrice":3000
... }
... ]
... }
... );
WriteResult({ "nInserted" : 1 })藉助 find() 方法顯示集合中的所有文件 -
> db.demo641.find();
這將生成以下輸出 -
{
"_id" : ObjectId("5e9c31d46c954c74be91e6e2"), "ProductId" : 101, "ProductInformation" :
[
{ "ProductName" : "Product-1", "ProductPrice" : 1000 },
{ "ProductName" : "Product-2", "ProductPrice" : 500 },
{ "ProductName" : "Product-3", "ProductPrice" : 2000 },
{ "ProductName" : "Product-4", "ProductPrice" : 3000 }
]
}以下是 MongoDB 中從嵌入陣列中獲取特定元素的查詢
> db.demo641.aggregate([
... {$unwind: "$ProductInformation"},
... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} },
... {$project: {_id: 0, ProductInformation: 1} }
... ]).pretty();這將生成以下輸出 -
{
"ProductInformation" : {
"ProductName" : "Product-1",
"ProductPrice" : 1000
}
}
{
"ProductInformation" : {
"ProductName" : "Product-3",
"ProductPrice" : 2000
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP