Eli Levit
Eli Levit

Reputation: 67

How to find only one obj in array by multiple conditions mongoose

I have a number of documents in the collection. Each document has houseNumber parameter and items array.

I need to find a right doc by houseNumber and then to find the right obj in items array by sku prop. Here is my performance:

StockLimitation.find({houseNumber: 2, 'items': {
    $elemMatch : { sku: 'YO-FA-01256-00' }
  }}, (err, data) => {
    if (err) console.log(err)
      console.log(data)
});

The problem is that whole items array is returned from actual doc but I need only one matched object. Is there solution for this?

UPDATE
Probably here is a solution: Retrieve only the queried element in an object array in MongoDB collection

BUT it returns only array element and I want the result with rest doc parameters such as houseNumber and name. How to do it?

document example

Upvotes: 1

Views: 1064

Answers (1)

Graciano
Graciano

Reputation: 518

The example show:

db.test.aggregate([
{$match: {'houseNumber': '125'}},
{$project: {
    shapes: {$filter: {
        input: '$items',
        as: 'item',
        cond: {$eq: ['$$item.sku', 'XYZ']}
    }},
    _id: 0, //0 means do not show the field
    houseNumber:1,
    number:1
 }}
])

Upvotes: 1

Related Questions