Please, help , I need to find count() of all _a[]._p[] elements having at least one of:
_a[]._p[].s.d.t[].dateP=2022 and _a[]._p[].s.d.t[].tF="N"
and
_a[]._p[].s.c.t[].dateP=2022 and _a[]._p[].s.c.t[].tF="N"
in following type of document:
{
"_id": ObjectId("5c05984246a0201286d4b57a"),
f: "x",
"_a": [
{
"_p": [
{
"pid": 2,
"s": {
"d": {
"t": [
{
id: 1,
"dateP": "20200-09-20",
},
{
id: 2,
"dateP": "2022-09-20",
"tF": "N"
}
]
},
"c": {
"t": [
{
id: 3,
"dateP": "20300-09-22"
},
{
id: 4,
"dateP": "2022-09-23",
"tF": "N"
}
]
}
}
}
]
}
]
}
In my attempt I can count only the documents that partially match the condition , but not sure if this is correct when there is more nested arrays and not sure how to do it faster and count the _p elements inside the _a:
db.collection.count({ "_a._p.s.c.t":{ $elemMatch:{ tF:"N" , dateP: /^2022/i } } })
The expected result from playground need to look as follow:
{ total: 1 }
Since the _a._p having s.d.t with id:2 and s.c.t with id:4 match the above condition
2
Answers
and the solution should be like:
update: only count element
MONGO_PALYGROUND
Here’s one way you can do it without
"$unwind"
, although the"$reduce"
nesting levels seem very error prone. I hope you test this with lots of data before depending on it.Try it mongoplayground.net.