1

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

Community
  • 1
  • 1
Eli Levit
  • 67
  • 8

1 Answers1

1

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
 }}
])
Graciano
  • 478
  • 4
  • 11
  • Works, thank you! But why it doesn't work this way I don't understand: `StockLimitation.findOne({houseNumber: 2}, {items: {$elemMatch: {sku: 'YO-FA-01256-00'}}}, (err,data) => { if (err) console.log(err) console.log(data); });` – Eli Levit Mar 28 '18 at 14:26
  • Might be something with Mongoose. If u execute the query using command line what do you get? – Graciano Mar 28 '18 at 14:40
  • $elemMatch is also a projection operator. So it limits the output https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/ – Graciano Mar 28 '18 at 14:56