1

i have document as given below:

{
    "_id" : ObjectId("999999b64655dea5e296de31b00"),
    "companies" : [ 
        {
            "companyId" : "ABC",
    
            "range" : {
                "start" : 0,
                "end" : 30
            }
        }, 
        {
            "companyId" : "DEF",
            "range" : {
                "start" : 20,
                "end" : 30
            }
        }, 
        {
            "companyId" : "CGH",
            "range" : {
                 "start" : 40,
                "end" : 50
           }
        }, 
         {
            "companyId" : "ABC",
    
            "range" : {
                "start" : 60,
                "end" : 90
            }
        }, 
   
    ],
      "createdTs" : NumberLong(1612407909406),
    "updatedTs" : NumberLong(1620891030125)
}

How to find "companyId" : "ABC" and return those elements only using $project?

I able to return the list using

db.getCollection('companyDetails').aggregate([
    {$match: {"companies.companyId": "ABC"}}, 
    {$project: {
        list: {$filter: {
            input: "$companies",
            as: "item",                     
            cond: {$eq:['$$item.companyId', 'ABC']}
         }}
    }}
]);

output :

{
    "_id" : ObjectId("999999b64655dea5e296de31b00"),
    "list" : [ 
        {
            "companyId" : "ABC",            
            "range" : {
                "start" : 0,
                "end" : 30
            }
        }, 
        {
            "companyId" : "ABC",           
            "range" : {
                "start" : 60,
                "end" : 90
            }
        }
    ]
}

But . i need list of range only instead of whole block

example: expected

{
    "_id" : ObjectId("999999b64655dea5e296de31b00"),
    "list" : [ 
        "range" : {
                "start" : 0,
                "end" : 30
            }, 
        "range" : {
                "start" : 60,
                "end" : 90
            }
    ]
}
turivishal
  • 34,368
  • 7
  • 36
  • 59
shree
  • 2,745
  • 7
  • 28
  • 35
  • 2
    Does this answer your question? [How to filter array in subdocument with MongoDB](https://stackoverflow.com/questions/15117030/how-to-filter-array-in-subdocument-with-mongodb) – turivishal May 13 '21 at 08:23
  • Thanks for your answer. i got it. but i am getting list with all data instead of range alone as list – shree May 13 '21 at 10:23

1 Answers1

1
  • $filter to iterate loop of companies and filter by companyId
  • $project stage to select only range field
db.collection.aggregate([
  { $match: { "companies.companyId": "ABC" } },
  {
    $project: {
      list: {
        $filter: {
          input: "$companies",
          cond: { $eq: ["$$this.companyId", "ABC"] }
        }
      }
    }
  },
  { $project: { "list.range": 1 } }
])

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59