检查字段在 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" }
广告