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

Làm cách nào để tìm bản ghi MongoDB sâu hai cấp?

Để tìm bản ghi MongoDB sâu hai cấp, hãy lặp lại bên trong MongoDB $ ở đâu. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> db.demo468.insertOne(
... {
... "_id" : new ObjectId(),
... "FirstPosition" : {
...    "StudentName" : "Chris",
...    "StudentAge" : 23
... },
... "SecondPosition" : {
...    "StudentName" : "David",
...    "StudentAge" : 20
... }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e804e2fb0f3fa88e2279069")
}
> db.demo468.insertOne(
... {
... "_id" : new ObjectId(),
... "FirstPosition" : {
...    "StudentName" : "Carol",
...    "StudentAge" : 21
... },
... "SecondPosition" : {
...    "StudentName" : "John",
...    "StudentAge" : 22
... }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e804fb0b0f3fa88e227906a")
}

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.demo468.find();

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

{ "_id" : ObjectId("5e804e2fb0f3fa88e2279069"), "FirstPosition" : { "StudentName" : "Chris",
"StudentAge" : 23 }, "SecondPosition" : { "StudentName" : "David", "StudentAge" : 20 } }
{ "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol",
"StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } }

Sau đây là truy vấn để tìm bản ghi MongoDB có độ sâu hai cấp -

> db.demo468.find({
... $where: function() {
...    for (var i in this) {
...       if (this[i]["StudentName"] == "John") {
...          return true;
...       }
...    }
...    return false;
... }
... })

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

{ "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol",
"StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } }