Computer >> Máy Tính >  >> Lập trình >> MongoDB

MongoDB Truy vấn kết hợp AND &OR?

Để kết hợp VÀ &HOẶC trong MongoDB, trước tiên chúng ta hãy tạo một bộ sưu tập với các tài liệu -

>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")
}

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

> db.combinedAndOrDemo.find().pretty();

Điều này sẽ tạo ra kết quả sau -

{
   "_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"
}

Sau đây là truy vấn cho AND &OR kết hợp -

> db.combinedAndOrDemo.find( {"$or":[ {"$and": [{"StudentFirstName": "John"}, {"_id": ObjectId("5cd306dcb64f4b851c3a13e2")}] }, {"StudentSkill" : "MongoDB" } ] } );

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5cd306dcb64f4b851c3a13e2"), "StudentFirstName" : "John", "StudentAge" : 23, "StudentSkill" : "MongoDB" }