What i want is to slice an array inside an array and return ONLY the queried array element. But i get instead every element from the first array.
I have this example input
[
{
"name": "admin",
"datasets": [
{
"name": "test",
"datapoints": [
1,
6,
4,
3,
8,
5,
3
],
"_id": {
"$oid": "619288f16733758444a28728"
}
},
{
"name": "more datasets",
"datapoints": [
1,
2,
3,
4,
5,
6,
7,
8
],
"_id": {
"$oid": "619289086733758444a2872a"
}
}
]
}
]
I have tried it with
db.collection.find({
name: "admin",
"datasets.name": "test"
},
{
"datasets.datapoints": {
$slice: [
0,
3
]
}
})
The problem here is that i get every item of datasets
[
{
"_id": ObjectId("5a934e000102030405000000"),
"datasets": [
{
"_id": ObjectId("619288f16733758444a28728"),
"datapoints": [
1,
6,
4
],
"name": "test"
},
{
"_id": ObjectId("619289086733758444a2872a"),
"datapoints": [
1,
2,
3
],
"name": "more datasets"
}
],
"name": "admin"
}
]
But i just need the 1
Result should just be:
{ datapoints: [1, 6, 4, 3] }
Query
name :"test" take the slice of the first 4 members$first or $arrayElemAt*on find criteria if you have too many admins, you can add also "datasets.name": "test" if you have index on "datasets.name" it can help.
aggregate(
[{"$match": {"name": {"$eq": "admin"}}},
{"$set":
{"datasets":
{"$map":
{"input": "$datasets",
"in":
{"$cond":
[{"$eq": ["$$this.name", "test"]},
{"datapoints": {"$slice": ["$$this.datapoints", 0, 4]},
"_id": "$$this._id",
"name": "$$this.name"},
null]}}}}},
{"$project":
{"_id": 0,
"datasets":
{"$filter":
{"input": "$datasets", "cond": {"$ne": ["$$this", null]}}}}}])