从MongoDB中的嵌入式数组获取特定元素?
要获取特定元素,请使用$match和点表示法。让我们创建一个包含文档的集合-
> 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
}
}热门推荐
4 祝福语简短古诗词
10 简短对公司的祝福语
11 身体康复的祝福语简短
12 提早庆祝生日祝福语简短
13 女生成年祝福语简短
14 公司开年仪式祝福语简短
15 周末祝福语简短的英语
16 老爸生日暴富祝福语简短
17 生日祝福语 简短独特高考
18 团队文案祝福语简短励志