在 MongoDB 中按属性名称搜索具有该属性的任何文档?
您可以为此使用$ne运算符。让我们首先创建一个包含文档的集合-
> db.searchByPropertyName.insertOne({"FirstName":"Larry","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cbaf7af7219729fde21ddb5") } > db.searchByPropertyName.insertOne({"FirstName":null,"Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cbaf7b97219729fde21ddb6") } > db.searchByPropertyName.insertOne({"FirstName":"John","Age":22}); { "acknowledged" : true, "insertedId" : ObjectId("5cbaf7c57219729fde21ddb7") } > db.searchByPropertyName.insertOne({"FirstName":null,"Age":25}); { "acknowledged" : true, "insertedId" : ObjectId("5cbaf7d07219729fde21ddb8") } > db.searchByPropertyName.insertOne({"FirstName":"David","Age":20}); { "acknowledged" : true, "insertedId" : ObjectId("5cbaf7df7219729fde21ddb9") }
以下是在find()prettyprint的帮助下显示集合中所有文档的查询-
> db.searchByPropertyName.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cbaf7af7219729fde21ddb5"), "FirstName" : "Larry", "Age" : 23 } { "_id" : ObjectId("5cbaf7b97219729fde21ddb6"), "FirstName" : null, "Age" : 21 } { "_id" : ObjectId("5cbaf7c57219729fde21ddb7"), "FirstName" : "John", "Age" : 22 } { "_id" : ObjectId("5cbaf7d07219729fde21ddb8"), "FirstName" : null, "Age" : 25 } { "_id" : ObjectId("5cbaf7df7219729fde21ddb9"), "FirstName" : "David", "Age" : 20 }
以下是按属性名称搜索具有该属性的任何文档的查询-
> db.searchByPropertyName.find({FirstName: { $ne : null } } ).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cbaf7af7219729fde21ddb5"), "FirstName" : "Larry", "Age" : 23 } { "_id" : ObjectId("5cbaf7c57219729fde21ddb7"), "FirstName" : "John", "Age" : 22 } { "_id" : ObjectId("5cbaf7df7219729fde21ddb9"), "FirstName" : "David", "Age" : 20 }