I have data where i need to get the count of lots the device had assigned for work. My data sample is of the following format
"_id" : ObjectId("5968c6aa5a44c946bc13d184"),
"listType" : "OPEN",
"resourceAssigned" : [
{
"deviceId" : "59522e01e67d9f1adcd7a158",
"capacity" : "2",
"lot" : NumberInt(1)
},
{
"deviceId" : "59522e01e67d9f1adcd7a158",
"capacity" : "7",
"lot" : NumberInt(2)
},
{
"deviceId" : "59522e01e67d9f1adcd7a158",
"capacity" : "5",
"lot" : NumberInt(3)
},
{
"deviceId" : "59522e01e67d9f1adcd7a151",
"capacity" : "6",
"lot" : NumberInt(1)
},
{
"deviceId" : "59522e01e67d9f1adcd7a151",
"capacity" : "3",
"lot" : NumberInt(2)
}
],
"materialHandlingUnit" : [
],
"__v" : NumberInt(0)
If i need to search ang get the count against deviceId key then it should return me count of number of times it is their in resourceAssigned array. What query can help me out for this?
Trial of building query from my side is:
var pickListId = req.body.pickListId;
var deviceId = req.body.deviceId;
var pipeline = [
{"$match": {"resourceAssigned.deviceId": deviceId}},
{"$unwind": "$resourceAssigned"},
{"$match": {"resourceAssigned.deviceId": deviceId}},
{
"$group": {
"_id": '$_id',
"numberOfEntries": {"$sum": 1}
}
}
];
pickListModel.aggregate(pipeline, function (err, pickAggregateRecord) {
if (err) {
res.json({message: 'INTERNAL SERVER ERROR, UNKNOWN SERVER ERROR HAS OCCURRED!!!!!', status: 'error', statusCode: '500'});
} else {
res.json(pickAggregateRecord);
}
});
The above query works but it does not have criteria for finding against specified '_id'. The query i want should work as findOne and not find.