如何从特定MongoDB文档内的对象数组中获取特定对象?
要从对象数组中获取特定对象,请使用位置运算符($)。首先让我们创建一个包含文档的集合-
> db.getASpecificObjectDemo.insertOne(... {
... _id :1,f
... "CustomerName" : "Larry",
... "CustomerDetails" : {
... "CustomerPurchaseDescription": [{
... id :100,
... "ProductName" : "Product-1",
... "Amount":10000
... },{
... id :101,
... "ProductName" : "Product-2",
... "Amount":10500
... },
... {
... id :102,
... "ProductName" : "Product-3",
... "Amount":10200
... }
... ]
... }
... }
... );
{ "acknowledged" : true, "insertedId" : 1 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.getASpecificObjectDemo.find().pretty();
这将产生以下输出-
{"_id" : 1,
"CustomerName" : "Larry",
"CustomerDetails" : {
"CustomerPurchaseDescription" : [
{
"id" : 100,
"ProductName" : "Product-1",
"Amount" : 10000
},
{
"id" : 101,
"ProductName" : "Product-2",
"Amount" : 10500
},
{
"id" : 102,
"ProductName" : "Product-3",
"Amount" : 10200
}
]
}
}
以下是从特定MongoDB文档内的对象数组中获取特定对象的查询-
> db.getASpecificObjectDemo.find({_id:1, "CustomerDetails.CustomerPurchaseDescription.id":101},{_id:0, "CustomerDetails.CustomerPurchaseDescription.$":1});
这将产生以下输出-
{ "CustomerDetails" : { "CustomerPurchaseDescription" : [ { "id" : 101, "ProductName" : "Product-2", "Amount" : 10500 } ] } }
以上是 如何从特定MongoDB文档内的对象数组中获取特定对象? 的全部内容, 来源链接: utcz.com/z/326585.html