將 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