簡體   English   中英

如何使用 mongoose find() 在數組中查找指定對象屬性的值

[英]How to find a value of a specified object property in a array using mongoose find()

我的架構

{
_id: xxxxxxxxxxxxx,
totalCreatedForms: [
{formName: "formone", formIndex: 0},
{formName: "formtwo", formIndex: 1},
{formName: "formthree", formIndex: 2}
]
}

我使用 mongoose 查詢來查找我需要的表單,如下所示:

db.collection.find({"totalCreatedForms.formName":"formtwo"}, data=>{res.send(data)})

有沒有辦法,我可以得到指定表單的formIndex的值。 這里我得到了“_id”的全部數據,我必須在前端再次過濾它。 但是,我想知道是否有查詢來獲取指定表單的值。

您需要以這種方式$運算符:

db.collection.find({
  "totalCreatedForms.formName": "formtwo"
},
{
  "_id": 0,
  "totalCreatedForms.formIndex.$": 1
})

查找查詢有兩個對象。

第一個匹配您要查找的元素。

第二個是指示哪些字段返回。 因此,不會返回_id字段,並且從數組中,只會返回放置位置運算符的索引。

輸出示例是這樣的:

[
  {
    "totalCreatedForms": [
      {
        "formIndex": 1
      }
    ]
  }
]

請注意,mongo 是一個存儲文檔並返回文檔的數據庫,因此這是僅獲取所需值而不是整個數組的最簡單方法(無需聚合)。

示例在這里

暫無
暫無

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

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