I am trying to find if type=conv is present in given rs, which is present in d --> ds --> rs --> type.
{
"_id" : ObjectId("5ec25873bd796ff191e695b1"),
"c_name" : "c1",
"t_name" : "t1",
"d" : [
{
"name" : "d1",
"ds" : [
{
"name" : "ds1",
"rs" : [
{
"type" : "conv"
}
]
}
]
},
{
"name" : "d2",
"ds" : [
{
"name" : "ds2",
"rs" : []
}
]
}
]
}
QUERY :
filter = {
"$and": [
{"c_name": {'$eq': 'c1'}},
{"t_name": {'$eq': 't1'}},
{"d.name": {'$eq': 'd2'}},
{"d.ds.name": {'$eq': 'ds2'}},
{"d.ds.rs.type": {'$eq': 'conv'}}
]
}
OUTPUT
It is returning me document, i guess it is looking for presence of type = conv in full document, even though it is not present on ds2 ( part of d2), but present on ds1 ( part of d1).
Do we have simpler way to find if it exists or not, I would like to first find and then using array filters, we can update the specific element inside deeply nested array.
Could someone please suggest how should I approach this problem? ( if we have any solution without using aggregation )
You need to use $elemMatch for these type of condition, And you can match strings without $eq operator
filter = {"$and": [
{"c_name": "c1"},
{"t_name": "t1"},
{ "d": { $elemMatch: { "name": "d2", "ds.name": "ds2" , "ds.rs.type": "conv"} } }
]}
With $elemMatch It will search only in the array where all condition will be true
Thanks @puneet, i need to try above. However, i am using now this
filter_query = {
"$and": [
{"c_name": {'$eq': 'c1'}},
{"t_name": {'$eq': 't1'}},
{
'd': {
'$elemMatch': {
'name': 'd2',
'ds': {
'$elemMatch':
{'name': 'ds2',
'rs':
{'$elemMatch':
{
"type": 'conv'}
}
}
}
}
}
}]}
This is also working !!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.