I need to fetch the data from multilevel document from MongoDB using aggregate function as per user input but not getting the result as expected. I am providing the format of document below.
{
"zone_list":[{
"zone":'NORTH',
"state_list":[{
"state":"DELHI",
"location_list":[{
"location":"NEW DELHI",
"task_list":[{
"login_id":"9937229853"
},{
"login_id":"9937229854"
}]
},{
"location":"AIRPORT",
"task_list":[{
"login_id":"9937229855"
}]
}]
},{
"state":"JK",
"location_list":[{
"location":"NEW JK",
"task_list":[{
"login_id":"9937229856"
},{
"login_id":"9937229857"
}]
},{
"location":"AIRPORT JK",
"task_list":[{
"login_id":"9937229858"
}]
}]
}]
},{
"zone":'EAST',
"state_list":[{
"state":"WB",
"location_list":[{
"location":"KOLKATA",
"task_list":[{
"login_id":"9937229859"
},{
"login_id":"9937229850"
}]
},{
"location":"ASAM",
"task_list":[{
"login_id":"9937229895"
}]
}]
},{
"state":"ODISHA",
"location_list":[{
"location":"BHUBANESWAR",
"task_list":[{
"login_id":"9937229844"
},{
"login_id":"9937229845"
}]
},{
"location":"AIRPORT BBSR",
"task_list":[{
"login_id":"9937229846"
}]
}]
}]
}]
}
The above is my inserted docs in database. Here I need to filter the data by matching the zone,state and location. Let's say user has input zone='NORTH' and state='DELHI' and location='AIRPORT'
so accordingly the corresponding record should fetched. I am using the below query but did not find the expected output.
db.collection.aggregate([
{$match:{}},
{$unwind:"$zone_list"},
{$unwind:"$state_list"},
{$match:{zone:zoneInput,state:stateInput}}])
.toArray((err,docs)=>{
if (!err) {
res.send(docs);
}
})
Here I am getting the blank output. I need if user is giving the zone,state and location
as input the respective result will be retrieved.
Looks like state_list
is nested inside zone_list
so second $unwind
is the problem here, try:
db.collection.aggregate([
{
$unwind: "$zone_list"
},
{
$unwind: "$zone_list.state_list"
},
{
$match: {
"zone_list.zone": "NORTH",
"zone_list.state_list.state": "DELHI",
"zone_list.state_list.location_list.location": "AIRPORT"
}
}
])
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.