1

I need some help with the following requirement, how would you do this in one batch, if this even possible in mongodb with nodejs?

I got multiple array's of 1000 id's from another source via the API. I need to get a result for each id.

Basically it should look like this:

const bulk = db.collection('profiles').initializeUnorderedBulkOp();

arrayWith1000TagIds.forEach((id) => {
  bulk
    .find({ tags: { $elemMatch: { _id: new ObjectId(id) } } })
    .count();

Unfortunately count is not a function of bulk. Any other way of doing this in one batch instead of doing a query for every id? In the end this is going to be 10k of queries.

Thank you. I'm pretty new to mongodb.

The result should look like this:

{
    [tagId]: 3, (There are 3 profiles, which include this specific tag in their tag list)
    [tagId]: 2,
    [tagId]: 0,
    ...
}

1 Answer 1

1

That is more easily done with a single aggregation, something like this:

db.collection.aggregate([
  {$unwind: "$tags"},
  {$match: {"tags._id" : {$in: arrayWith1000TagIds}}},
  {$group: {"_id" : "$tags._id", "count" : {$sum: 1}}}
])

(I have taken the liberty of assuming that "tags" is an array of objects, as suggested by your use of $elemMatch in your question).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.