Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

275
Views
Mongoose find all documents that have a string in an array

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 })
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!