要查找键何时未知,请使用$addField和$objectToArray。首先让我们创建一个包含文档的集合-
> db.demo375.insertOne( ... { ... "details":{ ... "Name":"John", ... "Age":23 ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a0ae42ae06a1609a00b06") } > db.demo375.insertOne( ... { ... "details":{ ... "Name":"David", ... "Age":21 ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a0ae42ae06a1609a00b07") } > db.demo375.insertOne( ... { ... "details":{ ... "Name":"David", ... "Age":22 ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a0ae42ae06a1609a00b08") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo375.find();
这将产生以下输出-
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b06"), "details" : { "Name" : "John", "Age" : 23 } } { "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } } { "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }
以下是查找键未知的查询-
> db.demo375.aggregate([ ... { "$addFields": { ... "UnknownKeys": { "$objectToArray": "$$ROOT" } ... }}, ... { "$match": { "UnknownKeys.v.Name": "David" }}, ... { "$project": { "UnknownKeys": 0 }} ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } } { "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }