简体   繁体   中英

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?

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

eg

db.collection.createIndex(
  { content_id: 1, isLocked: 1 } ,
  { name: "Content Id and isLocked" }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM