MongoDB 查询在 find() 中实现 OR 运算符


让我们创建一个带有文档的集合 -

> db.demo78.insertOne({"Name1":"Chris","Name2":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bd99c71bf0181ecc4228f")
}
> db.demo78.insertOne({"Name1":"Bob","Name2":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bd9ac71bf0181ecc42290")
}
> db.demo78.insertOne({"Name1":"David","Name2":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bd9b671bf0181ecc42291")
}
> db.demo78.insertOne({"Name1":"Jace","Name2":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bd9bf71bf0181ecc42292")
}

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

> db.demo78.find();

这将产生以下输出 -

{ "_id" : ObjectId("5e2bd99c71bf0181ecc4228f"), "Name1" : "Chris", "Name2" : "Mike" }
{ "_id" : ObjectId("5e2bd9ac71bf0181ecc42290"), "Name1" : "Bob", "Name2" : "Carol" }
{ "_id" : ObjectId("5e2bd9b671bf0181ecc42291"), "Name1" : "David", "Name2" : "Sam" }
{ "_id" : ObjectId("5e2bd9bf71bf0181ecc42292"), "Name1" : "Jace", "Name2" : "John" }

以下是 find() 中实现 OR 运算符的查询 -

> db.demo78.find({$or: [{"Name1": "Bob"}, {Name2: "John"}] });

这将产生以下输出 -

{ "_id" : ObjectId("5e2bd9ac71bf0181ecc42290"), "Name1" : "Bob", "Name2" : "Carol" }
{ "_id" : ObjectId("5e2bd9bf71bf0181ecc42292"), "Name1" : "Jace", "Name2" : "John" }

更新于:30-3-2020

83 次浏览

开启你的 职业生涯

完成课程获得认证

开始吧
广告