MongoDB: Make a projection to return just the first element of an array nested to another array nested to an object

597 views Asked by At

I have the following: I need to retrieve a document from MongoDB using a projection that returns only the first element of a list. However, this list is inside another one, and this one is inside an object, which is inside another object in the document. It looks like the following:

{
  "items": {
    "item": [
      {
        "items": {
          "item": [
            {
              "cell": [
                {
                  "value": "a"
                },
                {
                  "value": "b"
                },
                {
                  "value": "c"
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

My goal is to fetch it by value : "a" using a projection to avoid the other values. That is, my projection should return this:

{
  "items": {
    "item": [
      {
        "items": {
          "item": [
            {
              "cell": [
                {
                  "value": "a"
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

The problem is I 've already tried everything I know: I've used $elemMatch, $ and $slice to return just this first element, but I can't make a query to do it because the complexity of the document. I'm using MongoDB 3.2.

If you need more information, I update here. Anyway, thank you everybody!

1

There are 1 answers

1
s7vr On BEST ANSWER

You can try something like below. Makes use of $map operators to reach to the cell array while keeping the structure and uses $slice to pick the first value.

aggregate({
    $project: {
        items: {
            item: {
                $map: {
                    input: "$items.item",
                    as: "outer",
                    in: {
                        "items": {
                            item: {
                                $map: {
                                    input: "$$outer.items.item",
                                    as: "inner",
                                    in: {
                                        "cell": {
                                            $slice: ["$$inner.cell", 1]
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        _id: 0
    }
})