如何使用mongodb

时间:2019-06-20 12:08:04

标签: javascript mongodb mongoose aggregation-framework

我尝试使用mongodb迭代对象键值内部的数组,但无法正常工作。如何实现它。

数据库代码

db.product.aggregate([
    {
      $lookup: {
        from: "ecomm_prod_db_category",
        localField: "category_id",
        foreignField: "_id",
        as: "ordersetails"
      }
    },
    {
      $project: {
        product_name: 1,
        product_image: { $arrayElemAt: ["$product_image", 0] },
        ordersetails: 1
      }
    }
  ]).toArray();

我得到了输出

{ _id: 5cebc08af27fa0230090425a,
    product_name: 'Wires Solutions USB 2.0 Cable AM-BM 5Meters',
    ordersetails: [ {"name":"bourbon"} ],
    product_image: 'https://images-na.ssl-images-amazon.com/images/I/617XwKKAvzL._SX569_.jpg' }

例外的输出

{ _id: 5cebc08af27fa0230090425a,
  product_name: 'Wires Solutions USB 2.0 Cable AM-BM 5Meters',
  ordersetails: "bourbon",
  product_image: 'https://images-na.ssl-images-amazon.com/images/I/617XwKKAvzL._SX569_.jpg' }

2 个答案:

答案 0 :(得分:2)

您可以使用以下汇总

db.product.aggregate([
  { "$lookup": {
    "from": "ecomm_prod_db_category",
    "localField": "category_id",
    "foreignField": "_id",
    "as": "ordersetails"
  }},
  { "$project": {
    "product_name": 1,
    "product_image": { "$arrayElemAt": ["$product_image", 0] },
    "ordersetails": { "$arrayElemAt": ["$ordersetails.name", 0] }
  }}
]).toArray()

答案 1 :(得分:0)

如果orderdetails数组中有多个对象,则可以使用以下查询:

db.product.aggregate([
    {
      $lookup: {
        from: "ecomm_prod_db_category",
        localField: "category_id",
        foreignField: "_id",
        as: "ordersetails"
      }
    },
    {
      $project: {
        product_name: 1,
        product_image: { $arrayElemAt: ["$product_image", 0] },
        ordersetails: 1
      }
    }, 
    {
       $unwind: "ordersetails"
    },
    {
      $project: {
        product_name: 1,
        product_image: 1,
        ordersetails: "$ordersetails.name"}
      }
    }, 
  ]).toArray();