2

I tried to iterate array inside object key value using mongodb.but its not working.how to achieve it.

Database code


0

2 Answers 2

2

You can use below aggregation

db.product.aggregate([
  { "$lookup": {
    "from": "category",
    "localField": "id",
    "foreignField": "_id",
    "as": "ordersetails"
  }},
  { "$project": {
    "product_name": 1,
    "product_image": { "$arrayElemAt": ["$product_image", 0] },
    "ordersetails": { "$arrayElemAt": ["$ordersetails.name", 0] }
  }}
]).toArray()
Sign up to request clarification or add additional context in comments.

3 Comments

It will not work if you have more than one records in ordersdetails.
@RishabhGarg Please check the localField and the foreignField. It is targeting to _id of the other collection which means the record is unique. Hope you will get it.
@Fanpark Yes, True. Missed the _id.
0

If you have multiple object in orderdetails array then you can use the following query :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.