首页 > 解决方案 > 无论数组中的 ID 是否存在多次,如何获取由 ID 数组查询的文档

问题描述

我刚刚发现我可以在不使用循环的情况下在猫鼬中迭代 find()。通过做这个。

    const arrOfIds = reqBody.items.map(item => item.productId);


    Product.find({ '_id': { $in: arrOfIds }},(error, result)=>{


    const productList = collect(result).toArray();


})

但是我的问题是,如果数组(arrOfIds)中存在不止一次的 id,则 find() 方法仅将其视为一个存在,因此这是不正确的,因为我想对这些产品的价格求和,重复或不是。

我之前的代码是使用 map() 循环 find() 然后计算总和但与其他代码复杂,我只想要使用这个更简单的方法。无论是否有重复,我都可以让它返回每个 ID 的文档吗?

标签: javascriptnode.jsarraysmongodbmongoose

解决方案


假设 arrOfIds 是 ["product1", "product4", "product3", "product1", "product1" ] 那么你可以使用下面的聚合请参考 https://mongoplayground.net/p/1DtTtZWCHaH

db.collection.aggregate([
  {
    "$match": {
      _id: {
        $in: [
          "product1",
          "product4",
          "product3",
          "product1",
          "product1"
        ]
      }
    }
  },
  {
    "$set": {
      "totalPrice": {
        "$function": {
          "body": "function(arrOfIds,_id,price) {try { var total=0; arrOfIds.forEach((entry) => { if (entry=== _id){total= total+price;}})} catch (e) {row_number= 0;}return total;}",
          "args": [
            [
              "product1",
              "product4",
              "product3",
              "product1",
              "product1"
            ],
            "$_id",
            "$price"
          ],
          "lang": "js"
        }
      }
    }
  }
])

我们根据我们的数组匹配产品,然后我们根据出现的次数设置总价格,使用 set 通过实现函数来执行每个逻辑!它仍然是 foreach/loop 但在服务器端


推荐阅读