将 AND 和 OR 结合的 MongoDB 查询?
为了将 AND 和 OR 结合在 MongoDB 中,我们首先使用文档创建一个集合 −
>db.combinedAndOrDemo.insertOne({"StudentFirstName":"John","StudentAge":23,"StudentSkill":"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd306dcb64f4b851c3a13e2")
}
>db.combinedAndOrDemo.insertOne({"StudentFirstName":"Larry","StudentAge":21,"StudentSkill":"MySQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd306f3b64f4b851c3a13e3")
}
>db.combinedAndOrDemo.insertOne({"StudentFirstName":"Sam","StudentAge":24,"StudentSkill":"SQL Server"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd30701b64f4b851c3a13e4")
}以下是使用 find() 方法显示集合中所有文档的查询 −
> db.combinedAndOrDemo.find().pretty();
这将产生以下输出 −
{
"_id" : ObjectId("5cd306dcb64f4b851c3a13e2"),
"StudentFirstName" : "John",
"StudentAge" : 23,
"StudentSkill" : "MongoDB"
}
{
"_id" : ObjectId("5cd306f3b64f4b851c3a13e3"),
"StudentFirstName" : "Larry",
"StudentAge" : 21,
"StudentSkill" : "MySQL"
}
{
"_id" : ObjectId("5cd30701b64f4b851c3a13e4"),
"StudentFirstName" : "Sam",
"StudentAge" : 24,
"StudentSkill" : "SQL Server"
}以下是 AND 和 OR 的组合查询 −
> db.combinedAndOrDemo.find( {"$or":[ {"$and": [{"StudentFirstName": "John"}, {"_id": ObjectId("5cd306dcb64f4b851c3a13e2")}] }, {"StudentSkill" : "MongoDB" } ] } );这将产生以下输出 −
{ "_id" : ObjectId("5cd306dcb64f4b851c3a13e2"), "StudentFirstName" : "John", "StudentAge" : 23, "StudentSkill" : "MongoDB" }
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP