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

117
Views
mongodb filter documents from an array of ids

I have a collection in MongoDB which looks something like this

{
  "_id": ObjectId("62a2ef1084020f45678c8740"),
  "content_id": 436629,
  "isLocked": true,
  "type": "video",
  "created_at": ISODate("2022-06-10T12:43:20.563+05:30"),
  "updated_at": ISODate("2022-06-10T12:43:20.563+05:30"),
  "__v": 0
}

Assume there are thousands of this. Now i have an array of content_id coming from a diff api

[{
  "content_id": 123456
}, {
  "content_id": 456789
}, {
  "content_id": 453211
}....]

I want to check if the array has an id for which a doc exists in the collection and fulfils the condition "isLocked": false and increment a counter based on it. One solution would be to loop the array by for or map and run a find query to check each document one by one, like

for (let i = 0; i < array.length; i++) {
  let result = await db.collection.find({
    "content_id": array[i].content_id
  });
  if (result && result.length > 0 && result[0].isLocked === false) {
    counter++;
  }
}

This would not be an ideal solution as it would be very slow. Does Mongodb has something which can achieve the same results while being more performant or i am left with this solution?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

How about using $in?

array = array.map(item => item.content_id) // becomes ["id1", "id2","id3"...]

Then use following query

let result = await db.collection.find({ "content_id": { $in: array }, isLocked : false })

if you just want total number of resulted documents you can just result.length or replace .find with .countDocuments

For more performance, remember to index content_id + isLocked

e.g.

db.collection.createIndex(
  { content_id: 1, isLocked: 1 } ,
  { name: "Content Id and isLocked" }
)
about 4 years ago · Santiago Gelvez 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!