如何仅使用 MongoDB 聚合获取数组中的值?
让我们创建一个包含文档的集合——
> db.demo411.insertOne( ... { ... "Information" : [ ... { ... "Name1" : "Chris", ... "Name2" : "David" ... }, ... { ... "Name1" : "John", ... "Name2" : "John" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e70f19715dc524f70227682") }
借助 find() 方法显示集合中的所有文档——
> db.demo411.find();
这将生成以下输出——
{ "_id" : ObjectId("5e70f19715dc524f70227682"), "Information" : [ { "Name1" : "Chris", "Name2" : "David" }, { "Name1" : "John", "Name2" : "John" } ] }
以下是仅获取数组中值所用的查询——
> db.demo411.aggregate( ... [ ... {$project : { ... _id : 0, ... Information : {$map : {input : "$Information", as : "out", in : ["$$out.Name1", "$$out.Name2"]}} ... } ... } ... ] ... )
这将生成以下输出——
{ "Information" : [ [ "Chris", "David" ], [ "John", "John" ] ] }
广告