MongoDB 查询以多文档字段进行完全匹配


对于完全匹配,请将要匹配的值设置在 MongoDB 的 $in() 内。让我们先创建一个包含以下文档的集合 -

> db.demo422.insertOne({"Name":"Chris","Marks":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a4059822da45b30346e1")
}
> db.demo422.insertOne({"Name":"Chris","Marks":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a40a9822da45b30346e2")
}
> db.demo422.insertOne({"Name":"David","Marks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a4149822da45b30346e3")
}
> db.demo422.insertOne({"Name":"Sam","Marks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a41e9822da45b30346e4")
}
> db.demo422.insertOne({"Name":"David","Marks":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a4239822da45b30346e5")
}

使用 find() 方法从一个集合中显示所有文档 -

> db.demo422.find();

这将生成以下输出 -

{ "_id" : ObjectId("5e73a4059822da45b30346e1"), "Name" : "Chris", "Marks" : 34 }
{ "_id" : ObjectId("5e73a40a9822da45b30346e2"), "Name" : "Chris", "Marks" : 56 }
{ "_id" : ObjectId("5e73a4149822da45b30346e3"), "Name" : "David", "Marks" : 78 }
{ "_id" : ObjectId("5e73a41e9822da45b30346e4"), "Name" : "Sam", "Marks" : 45 }
{ "_id" : ObjectId("5e73a4239822da45b30346e5"), "Name" : "David", "Marks" : 89 }

以下是查询同时在多个文档字段上进行精确匹配的记录 -

> db.demo422.find({'$and': [{'Name': {'$in': ['Chris', 'David']}, 'Marks': {'$in': [34,89]}}]});

这将生成以下输出 -

{ "_id" : ObjectId("5e73a4059822da45b30346e1"), "Name" : "Chris", "Marks" : 34 }
{ "_id" : ObjectId("5e73a4239822da45b30346e5"), "Name" : "David", "Marks" : 89 }

更新于:03-四月-2020

671 浏览量

开启您的职业

通过完成该课程获得认证

立即开始
广告