检查MongoDB中是否存在字段?
您可以为此使用$exists运算符。首先让我们创建一个包含文档的集合-
>db.checkFieldExistsDemo.insertOne({"StudentFirstName":"John","StudentGender":"Male","StudentMongoDBScore":89}); { "acknowledged" : true, "insertedId" : ObjectId("5cd909611a844af18acdffbd") } >db.checkFieldExistsDemo.insertOne({"StudentFirstName":"Emma","StudentGender":"Female","StudentMongoDBScore":58}); { "acknowledged" : true, "insertedId" : ObjectId("5cd909781a844af18acdffbe") } >db.checkFieldExistsDemo.insertOne({"StudentFirstName":"Carol","StudentGender":"Male","StudentMongoDBScore":77}); { "acknowledged" : true, "insertedId" : ObjectId("5cd909871a844af18acdffbf") } >db.checkFieldExistsDemo.insertOne({"StudentFirstName":"David","StudentMongoDBScore":98}); { "acknowledged" : true, "insertedId" : ObjectId("5cd909a31a844af18acdffc0") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.checkFieldExistsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd909611a844af18acdffbd"), "StudentFirstName" : "John", "StudentGender" : "Male", "StudentMongoDBScore" : 89 } { "_id" : ObjectId("5cd909781a844af18acdffbe"), "StudentFirstName" : "Emma", "StudentGender" : "Female", "StudentMongoDBScore" : 58 } { "_id" : ObjectId("5cd909871a844af18acdffbf"), "StudentFirstName" : "Carol", "StudentGender" : "Male", "StudentMongoDBScore" : 77 } { "_id" : ObjectId("5cd909a31a844af18acdffc0"), "StudentFirstName" : "David", "StudentMongoDBScore" : 98 }
以下是检查MongoDB中是否存在字段的查询-
> db.checkFieldExistsDemo.find({"StudentMongoDBScore":98, "StudentGender":{"$exists": false}},{'StudentFirstName': 1, '_id':0});
这将产生以下输出-
{ "StudentFirstName" : "David" }