MongoDB 投影到指定的巢狀屬性?


對於特定巢狀屬性的投影,請在 MongoDB 中使用 aggregate()。讓我們先建立一個包含文件的集合 -

> db.demo379.insertOne(
...    {
...       "details1" : {
...          "details2" : {
...             "details3" : {
...                "10" : "John",
...                "50" : "Chris",
...                "40" : "David",
...                "30":"Mike"
...             }
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a94f82ae06a1609a00b10")
}

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

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

這將生成以下輸出 -

{
   "_id" : ObjectId("5e5a94f82ae06a1609a00b10"),
   "details1" : {
      "details2" : {
         "details3" : {
            "10" : "John",
            "30" : "Mike",
            "40" : "David",
            "50" : "Chris"
         }
      }
   }
}

以下是針對特定巢狀屬性的投影的查詢 -

> db.demo379.aggregate([
...    { "$addFields": {
...       "details1.details2.details3": {
...          "$arrayToObject": {
...             "$filter": {
...                "input": { "$objectToArray": "$details1.details2.details3" },
...                "as": "out",
...                "cond": {
...                   "$and": [
...                      { "$gte": ["$$out.k", "35"] },
...                      { "$lte": ["$$out.k", "60"] },
...                   ]
...                }
...             }
...          }
...       }
...    } }
... ])

這將生成以下輸出 -

{ "_id" : ObjectId("5e5a94f82ae06a1609a00b10"), "details1" : { "details2" : { "details3" : { "40" : "David", "50" : "Chris" } } } }

更新於: 2020-04-02

984 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始吧
廣告