如何从 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