如何找到包含指定字段的 MongoDB 文档?
要找到包含指定字段的文档,请使用 $exists。我们创建一个包含文档的集合 −
> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"Chris","ClientAge":34}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b2a31627c0c63e7dba69") } >db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"John","ClientLastName":"Smith","ClientAge":31}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b2be1627c0c63e7dba6a") } > db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientAge":33}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b2cd1627c0c63e7dba6b") } >db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientLastName":"Miller","ClientAge":31}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b2de1627c0c63e7dba6c") }
使用 find() 方法显示集合中的所有文档 −
> db.demo247.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5e46b2a31627c0c63e7dba69"), "ClientDetails" : [ { "ClientFirstName" : "Chris", "ClientAge" : 34 } ] } { "_id" : ObjectId("5e46b2be1627c0c63e7dba6a"), "ClientDetails" : [ { "ClientFirstName" : "John", "ClientLastName" : "Smith", "ClientAge" : 31 } ] } { "_id" : ObjectId("5e46b2cd1627c0c63e7dba6b"), "ClientDetails" : [ { "ClientFirstName" : "David", "ClientAge" : 33 } ] } { "_id" : ObjectId("5e46b2de1627c0c63e7dba6c"), "ClientDetails" : [ { "ClientFirstName" : "David", "ClientLastName" : "Miller", "ClientAge" : 31 } ] }
以下是对查询以找到包含指定字段的文档 −
> db.demo247.find({"ClientDetails.ClientLastName":{$exists:true}});
这将产生以下输出 −
{ "_id" : ObjectId("5e46b2be1627c0c63e7dba6a"), "ClientDetails" : [ { "ClientFirstName" : "John", "ClientLastName" : "Smith", "ClientAge" : 31 } ] } { "_id" : ObjectId("5e46b2de1627c0c63e7dba6c"), "ClientDetails" : [ { "ClientFirstName" : "David", "ClientLastName" : "Miller", "ClientAge" : 31 } ] }
广告