SHIVAM SHARMA
SHIVAM SHARMA

Reputation: 404

Extract only value in key value pair in $project in mongodb aggregate

I'm using mongo 3.4

I'm using the aggregate function of mongodb. My issue is that in $project I'm having a value as

{ $project: {
  "_id": 1,
  "name":1 ,
  ............
  ............
  "partners.address.country": 1,
  "partners.partnerName": 1,
} },
{ $match: matchCondition
}

In result , I'm getting value as

"partners" : {"address" : {"country" : " "}}

I don't want that I simply want it as

"partners" : {"country" : " "}

I want to skip address part. Also, I don't want to use .map function after the result as I have large data in $project. Can anybody help?

I have one more query this query is a join of 4 collections (2 others which I hadn't mention the above example). I want the whole record of my main collection & only 2-3 records of others collections, so, I have to write each & every record in $project and set it as 1. Is there a way through which we can skip to write each & every record in $project and still we can get the record in our result? Please help me! Thanks in advance

Upvotes: 4

Views: 3643

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

You can try as like below :

db.collection.aggregate({
  $project: {
    name: 1,
    "partners.country": "$partners.address.country", // a new field(country) will be created & a value will be assigned from given field
    "partners.partnerName": 1
  }
})

Test : MongoDB-Playground

Upvotes: 5

Related Questions