簡體   English   中英

如何在 MongoDB 中的數組中獲取嵌入文檔(使用 Mongoose)

[英]How to get embedded document in an array in MongoDB (with Mongoose)

我有一個像這樣保存在 MongoDB 中的 BSON 對象:

{
  "title": "Chemistry",
  "_id": "532d665f89ae4ae703b29730",
  "__v": 0,
  "sections": [
  {
    "week": 1,
    "_id": "532d665f89ae4ae703b29731",
    "assignments": [
    {
      "created_date": "2014-03-22T10:30:55.621Z",
      "_id": "532d665f89ae4ae703b29733",
      "questions": []
    },
    {
      "created_date": "2014-03-22T10:30:55.621Z",
      "_id": "532d665f89ae4ae703b29732",
      "questions": []
    }
    ],
    "materials": []
  }
  ],
  "instructor_ids": [],
  "student_ids": []
}

我想要做的是用 _id 532d665f89ae4ae703b29731 檢索“分配”。 它是指派數組中的一個元素,而后者又是sections 數組中的一個元素。

我能夠通過查詢檢索整個文檔

{'sections.assignments._id':assignmentId }

但是,我想要的只是分配子文檔

{
"created_date": "2014-03-22T10:30:55.621Z",
"_id": "532d665f89ae4ae703b29733",
"questions": []
}

有沒有辦法完成這樣的查詢? 我應該決定在不同的集合中分配嗎?

要檢索數組元素的子集,您需要使用$elemMatch投影運算符。

db.collection.find(
    {"sections.assignments._id" : assignmentId}, 
    {"sections.assignments":{$elemMatch:{"_id":assignmentId}}}
)

注意:

如果多個元素匹配$ elemMatch條件,則運算符將返回數組中的第一個匹配元素。

您可以像這樣進行匯總查詢:

db.collection.aggregate(
    {$unwind: "$sections"},
    {$unwind: "$sections.assignments"},
    {$match: {"sections.assignments._id": "532d665f89ae4ae703b29731"}},
    {$project: {_id: false, assignments: "$sections.assignments"}}
)

但是,我建議您考慮像您所說的那樣創建更多集合。 在我看來,更多的館藏似乎是比該查詢更好的解決方案。

$elemMatch 6.x 版開始,接受的答案不再有效,因為$elemMatch不能再用於嵌套文檔,而應使用aggregate

如果您想使用 _id 來查找文檔,您應該將作為參數獲得的 _id 轉換為原生 mongoDb _id 格式,否則它將被構造為字符串並且會發生錯誤。

    const native_id = mongoose.Types.ObjectId(id);
    const assignment = await <your_model_here>.aggregate([
      { $unwind: "$sections" },
      { $unwind: "$sections.assignments" },
      { $match: { "sections.assignments._id": native_id } },
      { $project: { _id: true, sections: "$sections.assignments" } }
    ]
    )
    console.log(assignment) // you have what you want

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM