首页 > 解决方案 > 如何在 mongodb 3.2 中从集合中添加多个文档

问题描述

如何在一个数组中获取所有“产品”详细信息,在一个array.im使用mongodb 3.2版本中获取所有“cartItems”

getCartProducts: (userId) => {
return new Promise(async (resolve, reject) => {
    let cartItems = await db.get().collection(collection.CART_COLLECTION).aggregate([
        {
            $unwind: "$products",
        },
        {
            $lookup: {
                from: collection.PRODUCT_COLLECTION,
                localField: "products",
                foreignField: "_id",
                as: "cartItems"
            }
        },
        {
            $match: {
                "product": { $ne: [] }
            }
        }
       
    ]).toArray()
    resolve(cartItems)
})
}

这是我得到的当前输出

[
  {
    _id: 5f9ff4b1183ac302703b28b1,
    user: 5f8fcdd5687bf506e44c9b4a,
    products: 5f845d073340762378ba1522,
    cartItems: [ [Object] ]
  },
  {
    _id: 5f9ff4b1183ac302703b28b1,
    user: 5f8fcdd5687bf506e44c9b4a,
    products: 5f9b94d1ab78c11b142646cb,
    cartItems: [ [Object] ]
  },
  {
    _id: 5f9ff4b1183ac302703b28b1,
    user: 5f8fcdd5687bf506e44c9b4a,
    products: 5f9b953bab78c11b142646cd,
    cartItems: [ [Object] ]
  }
]

这是我需要的我想要的输出。我在用着 mongodb 3.2

[ 
 {
    _id: 5f9ff4b1183ac302703b28b1,
    user: 5f8fcdd5687bf506e44c9b4a,
    products:[ 5f845d073340762378ba1522,5f9b94d1ab78c11b142646cb,5f9b953bab78c11b142646cd ]
    cartItems: [ [Object],[Object],[Object] ]
  }
]

标签: node.jsmongodb

解决方案


添加这个阶段:

操场

  {
    $group: {
      "_id": "$_id",
      user: {
        "$first": "$user"
      },
      cartItems: {
        $push: {
          $arrayElemAt: [
            "$cartItems",
            0
          ]
        }
      },
      products: {
        $push: "$products"
      }
    }
  }

推荐阅读