MongoDB中如何使用or运算符根据存在的情况取记录
要使用$or或基于存在来获取记录,请将$or与$exists一起使用。让我们创建一个包含文档的集合-
>db.demo185.insertOne({_id:101,details:{Name:"Chris",Score:78,Subjects:{"Name":"MySQL"}}}); { "acknowledged" : true, "insertedId" : 101 } > db.demo185.insertOne({_id:102,details:{Name:"Bob",Score:78}}); { "acknowledged" : true, "insertedId" : 102 } >db.demo185.insertOne({_id:103,details:{Name:"David",Score:78,Subjects:{"Name":"MongoDB"}}}); { "acknowledged" : true, "insertedId" : 103 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo185.find();
这将产生以下输出-
{ "_id" : 101, "details" : { "Name" : "Chris", "Score" : 78, "Subjects" : { "Name" : "MySQL" } } } { "_id" : 102, "details" : { "Name" : "Bob", "Score" : 78 } } { "_id" : 103, "details" : { "Name" : "David", "Score" : 78, "Subjects" : { "Name" : "MongoDB" } } }
以下是在MongoDB中使用或运算符的查询-
> db.demo185.find({ ... "$or": [ ... { "details.Subjects.Name": { "$exists": true } }, ... { "details.Subjects.Name": { "$exists": true } } ... ] ... })
这将产生以下输出-
{ "_id" : 101, "details" : { "Name" : "Chris", "Score" : 78, "Subjects" : { "Name" : "MySQL" } } } { "_id" : 103, "details" : { "Name" : "David", "Score" : 78, "Subjects" : { "Name" : "MongoDB" } } }