Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

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

Kết hợp $and và $or trong truy vấn. Tạo collection:

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

Hiển thị tất cả

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

Truy vấn: (StudentFirstName = "John" VÀ _id = ...) HOẶC StudentSkill = "MongoDB"

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

Kết quả (chỉ tài liệu John khớp cả hai nhánh OR):

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

Lưu ý: MongoDB ngầm hiểu AND ở cấp cao nhất của query object. $and tường minh cần khi cùng một trường xuất hiện nhiều lần hoặc kết hợp phức tạp.