Answer the question
In order to leave comments, you need to log in
Mongodb and subdocument search?
Let's say we have a collection document like this:
{
"objects": [
{
"a": 1,
"prop":2,
},
{
"a": 2,
"prop":3
}
]
}
{
"objects": { "$elemMatch": { "$and": [ {"a":1}, { "a":1} ]} }
}
{
"objects": [
{
"a": 1,
"prop":5
},
{
"a": 1,
"prop":6
}
]
}
Answer the question
In order to leave comments, you need to log in
In general, there is a solution to the problem and it is this:
db.test.aggregate([
{
"$redact": {
"$cond": [
{
"$eq": [
{
"$size": {
"$filter": {
"input": "$objects",
"as": "item",
"cond": {
"$eq": [
"$$item.a",
1
]
}
}
}
},
2
]
},
"$$KEEP",
"$$PRUNE"
]
}
}
])
db.users.find({'objects': {$elemMatch: {'a': 1}, $size: 2}})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question