如何仅显示嵌套 MongoDB 文档的键?
让我们创建一个文档集合 −
> 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" ] }
广告