簡體   English   中英

ZCCADCDEDB567ABAE643E15DCF0974E503Z 查找數組中包含字符串的所有文檔

[英]Mongoose find all documents that have a string in an array

我有一個問題:
如何使用 mongoose 在數組中找到所有包含字符串的文檔?

例如,我的文檔:

<Model>.findMany(/* code that i need */).exec() // return all documents that have an array called "tags" that includes tag "test"
{
  "_id": {
    "$oid": "61b129b7dd0906ad4a2efb74"
  },
  "id": "843104500713127946",
  "description": "Server di prova",
  "tags": [
    "developers",
    "programming",
    "chatting",
    "ita"
  ],
  "shortDescription": "Siamo un server nato per chattare e aiutare programmatori su Discord!",
  "invite": "https://discord.gg/NdqUqHBxz9",
  "__v": 0
}

例如,如果我需要獲取所有帶有ita標簽的文檔,我需要獲取此文檔。 如果文檔在數組標簽中沒有ita標簽,我不需要它並且代碼不會返回它。

在此先感謝,抱歉英語不好。

實際上,您可以只請求要測試的標簽,因為 mongoose 會查找每個標簽條目

所以這:

await Test.insertMany([{ tags: ["test"] }, { tags: ["Notest"] }])

let res = await Test.find({ "tags": "test" })
console.log(res)
    }

返回:

[
  {
    _id: new ObjectId("61b8af02c3effad21a5d7187"),
    tags: [ 'test' ],
    __v: 0
  }
]

2更整潔的事情要知道:

  1. 無論標簽有多少條目,這都有效,因為 long test 是其中之一
  2. 這也使您可以使用位置 $ 運算符更改包含“測試”的條目,因此 {$set: "tags.$": "smthNew"} 之類的內容將更改所有測試條目

第二個例子:

let res = await Test.updateMany({ "tags": "test" }, { $set: { "tags.$": "new" } }, { new: true })

暫無
暫無

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

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