让我们创建一个包含文档的集合-
> db.demo740.insertOne({ ... "details": ... [ ... { ... Name:"Chris", ... Age:21, ... CountryName:"US" ... }, ... { ... Name:"Bob", ... Age:20, ... CountryName:"UK", ... isMarried:true ... } ... ] ... }); { "acknowledged" : true, "insertedId" : ObjectId("5ead700c57bb72a10bcf066d") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo740.find();
这将产生以下输出-
"_id" : ObjectId("5ead700c57bb72a10bcf066d"), "details" : [ { "Name" : "Chris", "Age" : 21, "CountryName" : "US" }, { "Name" : "Bob", "Age" : 20, "CountryName" : "UK", "isMarried" : true } ] }
以下是查询以获取嵌套的MongoDB文档的密钥-
> db.demo740.aggregate([ ... { ... $project: { ... ListKeys: { ... $reduce: { ... input: "$details", ... initialValue: [], ... in: { ... $concatArrays: [ ... "$$value", ... { ... $map: { ... input: { ... $objectToArray: "$$this" ... }, ... in: "$$this.k" ... } ... } ... ] ... } ... } ... } ... } ... } ... ]).pretty()
这将产生以下输出-
{ "_id" : ObjectId("5ead700c57bb72a10bcf066d"), "ListKeys" : [ "Name", "Age", "CountryName", "Name", "Age", "CountryName", "isMarried" ] }