Reputation: 224
I'm trying to create an aggregation pipeline. The beginning of the code works okay. But when comes to the $match, the code returns nothing. Here is my code:
var userId = req.params.UserId
const measure = await Measure.aggregate([
{
$project: {
user: 1, creationDate: 1, WaterConsumption: 1
}
},
{
$match: {
user: userId
}
},
{
$group: {
_id: {
$dayOfMonth: "$creationDate"
},
waterConsumption: {$sum : "$WaterConsumption"}
}
}
]);
return res.json({measure})
My data is:
{
"measures": [
{
"creationDate": "2021-03-19T10:25:05.674Z",
"_id": "605870bffa87a605bf2a983a",
"avgPower": 8241,
"WaterConsumption": 22,
"avgTemperature": 45,
"shower": "5fb56ce7734b7e04b9c97c9b",
"user": "5f6cb0496a8c5a0deaa1a746"
},
{
"creationDate": "2021-03-19T10:25:05.674Z",
"_id": "605870d9fa87a605bf2a983b",
"avgPower": 8241,
"WaterConsumption": 22,
"avgTemperature": 45,
"shower": "5fb56ce7734b7e04b9c97c9b",
"user": "5f6cb0496a8c5a0deaa1a746"
},
{
"creationDate": "2021-03-17T10:25:05.674Z",
"_id": "605870ebfa87a605bf2a983c",
"avgPower": 4300,
"WaterConsumption": 32,
"avgTemperature": 28,
"shower": "5fb56d04734b7e04b9c97c9c",
"user": "5f6cb0496a8c5a0deaa1a746",
}...
]
The code runs perfect till it reaches the $match. If I console my userId it is a string with the user value "5f6cb0496a8c5a0deaa1a746". I don't know why $match is not working. The $group is working perfectly. I tried to swap the match to $match:{user: req.params.UserId} but the code keeps returning an empty array.
Upvotes: 0
Views: 224
Reputation: 57105
You are trying to match string with ObjectID that's why your $match
is not working.
Working demo with ObjectID - https://mongoplayground.net/p/Oz95gFwvp9X
const mongodb = require('mongodb');
const ObjectID = mongodb.ObjectID;
const userId = ObjectID(req.params.UserId); // convert your userid to ObjctedID format
Eg - userId - 5f6cb0496a8c5a0deaa1a746
will be converted to ObjectId("5f6cb0496a8c5a0deaa1a746")
Not working with string - https://mongoplayground.net/p/5PN8WeXt2zc
Upvotes: 2