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

Tìm tài liệu MongoDB có mảng chứa các thuộc tính cụ thể

Để tìm tài liệu mà mảng chứa nhiều thuộc tính cụ thể, sử dụng $and kết hợp dot notation (dấu chấm).

Tạo collection với mảng StudentInformation chứa object Name/Age:

> db.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e08b56e25ddae1f53b62219") }
> db.demo2.insertOne({"StudentInformation":[{"StudentName":"Carol","StudentAge":19},{"StudentName":"Bob","StudentAge":18}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e08b58625ddae1f53b6221a") }

Hiển thị dữ liệu (tài liệu 1: John+Mike, tài liệu 2: Carol+Bob):

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

Truy vấn $and: mảng phải chứa CẢ "Carol" VÀ "Bob" (trên trường StudentName):

> db.demo2.find({$and:[{"StudentInformation.StudentName":"Carol"},{"StudentInformation.StudentName":"Bob"}]});

Kết quả trả về tài liệu thứ 2 (có cả Carol và Bob):