在 MongoDB 中找不到已知 key 时怎么办?
如要查找未知 key,请使用 $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 } }
以下是查找未知 key 的查询 -
> 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 } }
广告