Home > Net >  Mongoose find all documents that have a string in an array
Mongoose find all documents that have a string in an array

Time:12-15

I've a question:
How i can find all documents that have a string in an array using mongoose?

For example, my document:

<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
}

For example, if I need to get all documents with ita tag, I need to get this document. If the document doesn't have ita tag in array tag, I don't need it and the code will not return it.

Thanks in advance and sorry for bad english.

CodePudding user response:

Actually you can just request tags to be test since mongoose looks for every tags entry

so this:

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

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

returns that:

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

2 more neat things to know:

  1. This works no matter how many entries tags has, as long test is one of ethem
  2. This also enables you to change the entrie containing the "test" by using positional $ operator, so something like {$set: "tags.$": "smthNew"} will change all the test entries

Example for 2nd:

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