0

I have a collection that looks something like:

[
  {
    "_id": 1,
    "title": "dummy title",
    "settings": [
      {
        "type": "light",
        "status": "enabled"
      },
      {
        "type": "flare",
        "status": "disabled"
      },
      {
        "type": "toolbar",
        "status": "enabled"
      }
    ]
  }
]

I wanna fetch it by Id but only with the "enabled" settings and not sure how the aggregation pipeline should look like.

I supposed to create the query using mongoTemplate in Java / Kotlin but even just the mongo query would be enough.

2 Answers 2

1

You can do it with a $filter

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      title: 1,
      settings: {
        $filter: {
          input: "$settings",
          as: "item",
          cond: {
            $eq: [
              "$$item.status",
              "enabled"
            ]
          }
        }
      }
    }
  }
])

try it here

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

Comments

1
//working code from MongoDB shell/CLI version 4.26(on windows 10 machine/OS)
> db.titles.find().pretty();
{
        "_id" : 1,
        "title" : "dummy title",
        "settings" : [
                {
                        "type" : "light",
                        "status" : "enabled"
                },
                {
                        "type" : "flare",
                        "status" : "disabled"
                },
                {
                        "type" : "toolbar",
                        "status" : "enabled"
                }
        ]
}
> db.titles.aggregate([
... {$unwind:"$settings"},
... {$match:{"settings.status":"enabled"}}
... ]);
{ "_id" : 1, "title" : "dummy title", "settings" : { "type" : "light", "status" : "enabled" } }
{ "_id" : 1, "title" : "dummy title", "settings" : { "type" : "toolbar", "status" : "enabled" } }
> print("MongoDB: ",db.version());
MongoDB:  4.2.6
>

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.