0

I have a collection called countries:

{
    "_id" : "123456",
    "enabled" : true,
    "entity" : {
            "name" : [
                    {
                            "locale" : "en",
                            "value" : "Lithuania"
                    },
                    {
                            "locale" : "de",
                            "value" : "Litauen"
                    }
            ]
    }
}

I like to return only the ObjectId and the value when the locale is "en".

 {"_id":"123456", "value":"Lithuania"}

Ideally renaming value to country for:

 {"_id":"123456", "country":"Lithuania"}

Using a projection like:

db.countries.aggregate([
    {$project: 
        {country: {$arrayElemAt:["$entity.name",0]}}
    }
])

returns almost the desired results:

 {"_id" : "1234565", "country" : { "locale" : "en", "value" : "Lithuania" } }

3 Answers 3

1

This this one:

db.collection.aggregate([
  {
    $set: {
      country: {
        $filter: {
          input: "$entity.name",
          cond: { $eq: [ "$this.locale", "en" ] }
        }
      }
    }
  },
  { $project: { country: { $first: "$country.value" } } },
])

See Mongo playground

Sign up to request clarification or add additional context in comments.

Comments

1

You can try,

  • $reduce to iterate loop of entity.name array, $cond check locale is "en" then return value
db.collection.aggregate([
  {
    $project: {
      country: {
        $reduce: {
          input: "$entity.name",
          initialValue: "",
          in: {
            $cond: [
              { $eq: ["$$this.locale", "en"] },
              "$$this.value",
              "$$value"
            ]
          }
        }
      }
    }
  }
])

Playground

Comments

1

I should have specified the MongoDB Version. Server is running 3.6.20. For that the following solution works:

db.countries.aggregate([
  {
    $addFields: {
      country: {
        $filter: {
          input: "$entity.name",
          cond: { $eq: [ "$$this.locale", "en" ] }
        }
      }
    }
 },
  { $project: { country: { $arrayElemAt: [["$country.value"],0] } } },
])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.