在mongodb nodejs中批量多个查询

时间:2018-04-15 14:40:25

标签: node.js mongodb

我需要一些关于以下要求的帮助,如果在使用nodejs的mongodb中甚至可以实现这一点,你将如何在一个批次中执行此操作?

我通过API从另一个来源获得了1000个id的多个数组。我需要为每个id获得一个结果。

基本上它应该是这样的:

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

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

不幸的是count不是批量函数。在一个批处理中执行此操作的任何其他方式,而不是对每个ID进行查询?最后这将是10k的查询。

谢谢。我对mongodb很新。

结果应如下所示:

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

1 个答案:

答案 0 :(得分:0)

使用单个aggregation更容易做到这一点,如下所示:

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

(我冒昧地假设"标签"是一个对象数组,正如您在问题中使用$ elemMatch所建议的那样。)

相关问题