为此,请使用$addFields。在这种情况下,使用$objectToArray以键和值的形式获取数据。将$filter和$indexOfBytes一起使用以检查是否有任何键。在里面。
首先让我们创建一个包含文档的集合-
> db.demo364.insertOne( ... { ... "details" : { ... "details1.otherdetails.Name" : {"FirstName":"Chris" } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e57d485d0ada61456dc936d") } > db.demo364.insertOne( ... { ... "details" : { ... "details1.otherdetails.Name" : {"FirstName":"David" } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e57d486d0ada61456dc936e") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo364.find();
这将产生以下输出-
{ "_id" : ObjectId("5e57d485d0ada61456dc936d"), "details" : { "details1.otherdetails.Name" : { "FirstName" : "Chris" } } } { "_id" : ObjectId("5e57d486d0ada61456dc936e"), "details" : { "details1.otherdetails.Name" : { "FirstName" : "David" } } }
以下是查找带有包含点的键的记录的查询-
> db.demo364.aggregate([ ... { ... $addFields: { ... result: { ... $filter: { ... input: { $objectToArray: "$details" }, ... cond: { ... $ne: [ { $indexOfBytes: [ "$$this.k", "." ] } , -1 ] ... } ... } ... } ... } ... }, ... { ... $match: { ... $expr: { ... $ne: [ { $size: "$result" }, 0 ] ... } ... } ... }, ... { ... $project: { ... result: 0 ... } ... } ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e57d485d0ada61456dc936d"), "details" : { "details1.otherdetails.Name" : { "FirstName" : "Chris" } } } { "_id" : ObjectId("5e57d486d0ada61456dc936e"), "details" : { "details1.otherdetails.Name" : { "FirstName" : "David" } } }