[英]Mongoose: Find all documents with array field which is included in another array
[英]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更整潔的事情要知道:
第二個例子:
let res = await Test.updateMany({ "tags": "test" }, { $set: { "tags.$": "new" } }, { new: true })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.