Reputation: 3
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!
Upvotes: 0
Views: 598
Reputation: 75914
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
}
})
Upvotes: 1