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!
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.