0

I'm currently working with mongodb (mongoose). One of my example documents is:

myuser{
  _id: 7777...,
  money: 1000,
  ships:[{
    _id: 7777...
    name: "myshipname",
    products:[{
      product_id: 7777....,
      quantity: 24
    }]
  }
}

What I aim to do is to get a certain product given user id, ship id and product id, being the result something like: { product_id: 777..,quantity:24}

So far I got to find a certain user ship with:

findOne(userId,ships:{ $elemMatch: {_id:shipId}})

Which returns the information of the ship with shipId inside the array ships from user with userId. However, I cannot find the way to get only a certain product from that ship

1 Answer 1

1

What you want can probably best be done using the aggregation framework. Something like:

db.users.aggregate([
  {$match: { _id : <user>}},
  {$unwind: "$ships"},
  {$unwind: "$ships.products"},
  {$match: { "ships._id": <ship>}},
  {$match: { "ships.products.product_id": <product>}}
]);

Note I'm not on a computer with mongo right now, so my syntax might be a bit off.

Sign up to request clarification or add additional context in comments.

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.