让我们首先创建一个集合。以下是使用文档创建集合的查询
> db.documentExistsOrNotDemo.insertOne({"UserId":101,"UserName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9932bd330fd0aa0d2fe4cf")
}
> db.documentExistsOrNotDemo.insertOne({"UserId":102,"UserName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9932c6330fd0aa0d2fe4d0")
}
> db.documentExistsOrNotDemo.insertOne({"UserId":102,"UserName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9932ce330fd0aa0d2fe4d1")
}以下是在find()方法的帮助下显示集合中所有文档的查询
> db.documentExistsOrNotDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5c9932bd330fd0aa0d2fe4cf"),
"UserId" : 101,
"UserName" : "John"
}
{
"_id" : ObjectId("5c9932c6330fd0aa0d2fe4d0"),
"UserId" : 102,
"UserName" : "Chris"
}
{
"_id" : ObjectId("5c9932ce330fd0aa0d2fe4d1"),
"UserId" : 102,
"UserName" : "Robert"
}情况1:以下是如果文档存在则返回true的查询
> db.documentExistsOrNotDemo.find({"UserId":101}).count() > 0;这将产生以下输出
True
情况2以下是如果不存在文档则返回false的查询
> db.documentExistsOrNotDemo.find({"UserId":110}).count() > 0;这将产生以下输出
False