让我们创建一个包含文档的集合-
> 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" ] ] }