【问题标题】:How to get documents queried by array of IDs regardless if the ID's in the array exists more than once无论数组中的 ID 是否存在多次,如何获取由 ID 数组查询的文档
【发布时间】:2021-11-06 15:28:00
【问题描述】:

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

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


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


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


})

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

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

【问题讨论】:

    标签: javascript node.js arrays mongodb mongoose


    【解决方案1】:

    假设 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,但在服务器端

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 2023-04-02
      • 2013-09-06
      相关资源
      最近更新 更多