Govind
Govind

Reputation: 267

$filter array in mongodb

I need your help to get data from collection with and condition. Suppose I have a collection having below document and I need search on sub document field named brandId having value of 14 and 38.

{
    "_id" : ObjectId("5b3b206c4a25da19d05f41a2"),
    "models" : [ 
        {
            "brandId" : "14",
            "modelId" : "100",
            "brandSlug" : "honda",
            "modelSlug" : "hrv"
        }, 
        {
            "brandId" : "38",
            "modelId" : "894",
            "brandSlug" : "toyota",
            "modelSlug" : "fortuner"
        }, 
        {
            "brandId" : "38",
            "modelId" : "894",
            "brandSlug" : "toyota",
            "modelSlug" : "fortuner"
        }, 
        {
            "brandId" : "37",
            "modelId" : "773",
            "brandSlug" : "suzuki",
            "modelSlug" : "ertiga"
        } 
    ]
}

I want that sub documents which brandId is 14 and 38.

Desired Output =>

{
    "_id" : ObjectId("5b3b206c4a25da19d05f41a2"),
    "models" : [ 
        {
            "brandId" : "14",
            "modelId" : "100",
            "brandSlug" : "honda",
            "modelSlug" : "hrv"
        }, 
        {
            "brandId" : "38",
            "modelId" : "1240",
            "brandSlug" : "toyota",
            "modelSlug" : "kijang-innova"
        }, 
        {
            "brandId" : "38",
            "modelId" : "894",
            "brandSlug" : "toyota",
            "modelSlug" : "fortuner"
        } 
    ]
}

Upvotes: 1

Views: 113

Answers (2)

matthPen
matthPen

Reputation: 4343

Why be so complicated? Unwind,match and group will do the job perfectly.

db.test1.aggregate([
            {
                $unwind: {
                    path : "$models"
                }
            },
            {
                $match: {
                $or:[{"models.brandId":"14"},{"models.brandId":"38"}]
                }
            },
            {
                $group: {
                _id:"$_id",
                models:{$push:"$models"}
                }
            },
        ]
    );

Upvotes: 1

Ashh
Ashh

Reputation: 46441

You can try $filter aggregation with $or operator

db.collection.aggregate([
  {
    "$addFields": {
      "models": {
        "$filter": {
          "input": "$models",
          "as": "model",
          "cond": {
            "$or": [
              {
                "$eq": [
                  "$$model.brandId",
                  "14"
                ]
              },
              {
                "$eq": [
                  "$$model.brandId",
                  "38"
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Upvotes: 0

Related Questions