【问题标题】:Mongoose find all documents that have a string in an arrayMongoose 查找数组中包含字符串的所有文档
【发布时间】:2022-01-17 20:49:50
【问题描述】:

我有一个问题:
如何使用 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标签,我不需要它,代码也不会返回它。

在此先感谢,抱歉英语不好。

【问题讨论】:

  • 您能否提供一个示例文档和预期的示例结果
  • @MaximilianDolbaum 完成

标签: arrays mongodb mongoose document


【解决方案1】:

实际上你可以只请求标签进行测试,因为 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. 无论标签有多少条目,这都有效,只要 test 是其中之一
  2. 这还使您可以使用位置 $ 运算符更改包含“测试”的条目,因此 {$set: "tags.$": "smthNew"} 之类的内容将更改所有测试条目

第二个例子:

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

【讨论】:

  • 感谢您的解决方案!
猜你喜欢
  • 2014-06-04
  • 2012-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
相关资源
最近更新 更多