Hongbo Miao
Hongbo Miao

Reputation: 49984

Select without using $unwind (Mongoose aggregation)

I am using Mongoose's aggregation (MongoDB v3.2). There are two items factory1 and factory2 in database. Each factory has a field products which is a array.

I want to select all factories which has product code1=='aa' & code2=='BB'

// factory1.products
[{
  code1: 'aa',
  code2: 'AA'
}, {
  code1: 'bb',
  code2: 'BB'
}]

// factory2.products
[{
  code1: 'aa'
  code2: 'BB'
}]

This is how I do now:

Factory
  .aggregate([
    { $unwind: '$products' },  // Ensure get factory2 only when use $match. Without $unwind, will get both factory1 and factory2
    { $match: {
      'products.code1': 'aa',
      'products.code2': 'BB'
    }}
  ]);

Is there a way to select without using $unwind? Because later I want to get the complete items again. Thanks

Upvotes: 0

Views: 250

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312129

Change your $match to use $elemMatch to require that both terms be satisfied by the same products element:

Factory.aggregate([
  { $match: { products: { $elemMatch: {
    code1: 'aa',
    code2: 'BB'
  }}}}
]);

Upvotes: 2

Related Questions