0
{
   "_id" : ObjectId("5b04e9d891081234f8b69199"),
   "simpleType" : "somethingSomething",
   "embeddedArray" : [
                {
                  "type" : "theTypeIWant",
                  "data" : [...]
                },
                {
                  "type" : "notThatOne",
                  "data" : [...]
                },
                {
                  "type" : "notThatOne",
                  "data" : [...]
                },
                {
                  "type" : "notThatOne",
                  "data" : [...]
                },
                {
                  "type" : "notThatOne",
                  "data" : [...]
                }
        ]
}

I have a collection which the documents are structured like my sample above. I already started with an aggregation to match the type I want, but I get the whole array with it which I don't want.

db.collection.aggregate(
    [
        {$project: {"simpleType" : 1, "embeddedArray.type": 1, "embeddedArray.data": 1}},
        {$match: {"embeddedArray.type" : "theTypeIWant"}}
    ]
)

Is there a way to get only that element of the embeddedArray, that matches the type I am searching for, for my projection?

I cannot guarantee that the element with the type I am searching for will always be the first element in my embedded array.

I would like to have a result set like following:

{
    "simpleType" : "somethingSomething",
    "type": "theTypeIWant",
    "data": [...]
}

or:

{
    "simpleType" : "somethingSomething",
    "embeddedArray":{
        "type": "theTypeIWant",
        "data": [...]
    }
}
  • Your question title literally typed right into google goes straight to the documentation of the relevant operator. Please search before posting questions. – Neil Lunn May 24 '18 at 10:27
  • @NeilLunn I had some troubles to form my question (for googling it), that's is why I wrote an explanation for my problem here. With those structured thoughts I could've started my searching again, but I hit the submit button too quickly. Thank you for you fast feedback. I will try to be more considerate before submitting a question in the future. – jrltgronic May 24 '18 at 10:35

0 Answers0