0

Schema:

new Schema({
    productId: String,
    types: [{
        productType: String,
        lastModified: Date
    }]
});

Query:

{
  productId: "1",
  email: "test@test.com",
  productType: "test",
}

I tried this but its returning only first matched element:

const productType = 'test';
const result = await this.model(email)
.find(
    { productId, 'types.productType': productType },
    { 'types.$': productType }
).lean();

with aggregate, it return empty array result:

const result = await this.model(email).aggregate([
    { $match: { productId, 'types.productType': 'productType' } },
    {
        $project: {
            types: {
                $filter: {
                    input: '$types',
                    as: 'r',
                    cond: { $eq: ['$$r.productType', productType] }
                }
            },
            _id: 0
        }
    }
]);

I need to find all matching elements where projection $ returns the first matched

kittu
  • 6,662
  • 21
  • 91
  • 185
  • Please share your document structure – Vivek Bani Jul 23 '21 at 11:27
  • Does this answer your question? [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – turivishal Jul 23 '21 at 11:30
  • @RajdeepDebnath Added schema – kittu Jul 23 '21 at 12:51
  • Ok, you do not need projection. `this.model(email) .find( { productId, 'types.productType': productType },).lean()` will return all matching elements – Vivek Bani Jul 23 '21 at 12:56
  • @RajdeepDebnath If I don't use projection then its returning only `{ productType: 'test'}` instead of all properties in object – kittu Jul 23 '21 at 13:14
  • Well, it should return everything if you don't use projection. Can you share some data, then I can test your query? – Vivek Bani Jul 23 '21 at 13:17
  • `{` `productID: "1",` `email: "test@test.com",` `productType: "test"` `}` – kittu Jul 23 '21 at 13:36
  • @RajdeepDebnath its okay I figured it out. Thanks – kittu Jul 23 '21 at 14:01

0 Answers0