如何查詢兩層深的 MongoDB 記錄?


要查詢兩層深的 MongoDB 記錄,請在 MongoDB $where 內進行迴圈。讓我們建立一個包含文件的集合 −

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

在集合中使用 find() 方法顯示所有文件 −

> db.demo468.find();

這將產生以下輸出 −

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

以下是對 MongoDB 中兩級深記錄進行查詢 −

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

這將產生以下輸出 −

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

更新日期:2020 年 5 月 11 日

241 次瀏覽

開啟你的職業 生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.