I have following schema with colletcion & there values associated with it my mongodb. And following is example document of this one.
{
"_id" : ObjectId("590d46d685a155f33a4a1f1d"),
"domainName" : "gmail.com",
"userlevels" : [
{
"labId" : 104,
"userlevel" : true
},
{
"labId" : 401,
"userlevel" : false
},
{
"labId" : 202,
"userlevel" : true
},
{
"labId" : 102,
"userlevel" : true
},
{
"labId" : 108,
"userlevel" : true
},
{
"labId" : 110,
"userlevel" : true
},
{
"labId" : 120,
"userlevel" : true
},
{
"labId" : 820,
"userlevel" : false
}
],
"labconfigs" : [
ObjectId("590d46d685a155f33a4a1f0c"),
ObjectId("590d46d685a155f33a4a1f11"),
ObjectId("590d46d685a155f33a4a1f10"),
ObjectId("590d46d685a155f33a4a1f0d"),
ObjectId("590d46d685a155f33a4a1f12"),
ObjectId("590d46d685a155f33a4a1f0f"),
ObjectId("590d46d685a155f33a4a1f0e"),
ObjectId("591087b0b18c5f472905343a")
]
}
So what we want is all documents matching within particular range of labID, with only fields which are matching in array ("userlevels") to be in result output.
Say if we want all matching documents in collection with range between $gt 100 to lt 200 , then following desired output should come.
{
"_id" : ObjectId("590d46d685a155f33a4a1f1d"),
"domainName" : "gmail.com",
"userlevels" : [
{
"labId" : 104,
"userlevel" : true
},
{
"labId" : 102,
"userlevel" : true
},
{
"labId" : 108,
"userlevel" : true
},
{
"labId" : 110,
"userlevel" : true
},
{
"labId" : 120,
"userlevel" : true
}
]
}
What i have tried & this is my mongodb query.
db.collection('domains').find({
"userlevels":{ $all :[
{ "$elemMatch" : { "labId" :{$gte : 100, $lt:200 }}}
]}
}).toArray(function(err, items) {
console.log("items",items);
});
It replies with all documents matching documents within range of lab_id's (100 to 200) , but it replies in userlevels with lab_id's.