检查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" }热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短