I am trying to learn mongoose, I come from a SQL background and I am having difficulties figuring out how this works.
So I am essentially trying to run this SQL code in Mongoose
$sql = "SELECT SUM(comdataPurchase)
FROM fuel566243
WHERE fuelDate BETWEEN '$startDate' AND '$endDate';";
But I cannot get it to work properly for me in mongoose. Here is what I have so far.
FuelReceipt.aggregate([{$match:{date:{$gte: fuelStart, $lt: fuelEnd}}},
{$group:{truckNumber: truckNumber, dieselGallons:{'$sum': '$count'}}}]).exec(function(err, data){
if(err){
console.log('Error Fetching Model');
console.log(err);
}
console.log(data);
});
Thank you in advance for your help <3
edit:-------------
This works:
FuelReceipt.aggregate([
{$group:{_id: '$truckNumber',
dieselGallons:{$sum: '$dieselGallons'}}}]).exec(function(err, data){
if(err){
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
});
This gives empty array:
FuelReceipt.aggregate([
{$match:{date:{$gte: fuelStart, $lte: fuelEnd}}},
{$group:{_id: '$truckNumber',
dieselGallons:{$sum: '$dieselGallons'}}}]).exec(function(err, data){
if(err){
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
});
edit 2:----------------
I figured it out, had to change the data type for the start and end dates.
FuelReceipt.aggregate([
{$match:{date:{$gte: new Date(fuelStart), $lte: new Date(fuelEnd)}}},
{$group:{_id: '$truckNumber',
fuelCost:{$sum: '$fuelCost'}}}]).exec(function(err, data){
if(err){
console.log('Error Fetching Model');
console.log(err);
}
res.send(data);
console.log(JSON.stringify(data, null));
});
The "between" part is implemented correctly however $group requires _id value. You can set it to null if you want to get single aggregate for entire set of documents:
{$group: { _id: null, dieselGallons: {'$sum': '$comdataPurchase'}}}
Related
I'm trying to return the updated document from mongodb but instead I'm console logging Null, any ideas why this might be happening? It's updating the document in the database, but it doesn't seem to want to return the full document to me so I can console log it.
User.findOneAndUpdate({userEmail}, {$set: {resetPasswordToken: token, resetPasswordExpires: now}}, function (err, res){
console.log(res);
})
Use the {new: true} option.
User.findOneAndUpdate({
email: userEmail
}, {
$set: {
resetPasswordToken: token,
resetPasswordExpires: now
}
}, {
new: true
}, function(err, res) {
console.log(res);
})
So I am trying to find all documents in a database between 'X' and 'X' dates and then order those by userID. This is what I have so far:
await Expense.find(
{'date' :{'$gte': new Date(startDate), '$lte': new Date(endDate)}}),{sort: {_id: 1}}.exec(function(err, data){
if(err){
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
expenseArray = data;
console.log(expenseArray);
But it keeps giving me "TypeError: {(intermediate value)}.exec is not a function"
For added clarification I am trying to write this in mongoose:
"SELECT employeeName, SUM(amount)
FROM reimbursements
WHERE d8 BETWEEN '$startDate' AND '$endDate'
GROUP BY employeeName
ORDER BY employeeName;";
What am I doing wrong? Thank you in advance :D
Your query has few syntax issues, Please try this :
Update :
Below old code will work, but it would be better if you try this way :
try {
let data = await Expense.find(
{ 'date': { '$gte': new Date(startDate), '$lte': new Date(endDate) } }).sort({ _id: 1 })
/** .find() will not return null, it will either return [] or [with matched docs] */
if (data.length) { // checks data != []
console.log(data)
} else { // data == []
console.log('Empty - no docs found')
}
} catch (error) {
console.log('Error Fetching Model');
console.log(error);
}
Old :
await Expense.find(
{ 'date': { '$gte': new Date(startDate), '$lte': new Date(endDate) } }).sort({ _id: 1 }).exec(function (err, data) {
/** sort is not an option for .find() not like aggregate, it has to be on cursor which is result of .find() & .exec() should be at end which is either .find() or .sort() */
if (err) {
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
expenseArray = data;
console.log(expenseArray)
})
Sample : mongooseModel.find().sort().exec()
Ref : cursor.sort
How to update metadata in mongoDB(Nodejs).
gfs.collection('uploads').updateOne({ filename:image}, {$set:
{metadata.likes:1}},
function(err, res) {
if (err) throw err;
console.log("1 document updated");
});
As your code will work if you add metadata.likes in brackets like
gfs.collection('uploads').updateOne({ filename:image}, {$set:
{'metadata.likes':1}},
function(err, res) {
if (err) throw err;
console.log("1 document updated");
});
In this case "metadata.likes" would be equal to 1. Every time it will update it and set it to 1. If you want to increment "metadata.likes" by 1, so try this
gfs.collection('uploads').updateOne({ filename:image}, {$inc:
{'metadata.likes':1}},
function(err, res) {
if (err) throw err;
console.log("1 document updated");
});
I have some trouble making queries inside a callback running in Meteor Mongo. Anyone is seeing what I am doing wrong here? Thanks!
var houseInserted = Houses.insert({
building_number: address.building_number,
},function(error, results){
if(error) throw error;
console.log(results); // runs
Meteor.users.update( { _id: this.userId }, // Does not execute
{ $set: { 'profile.housed': true , 'profile.address' : results }
}, function(err, doc){
if (err) throw err;
console.log(results); // runs
console.log(doc);
});
console.log(results); // runs
}
);
I want to get all stream data with thread value but not including null. On my mongodb console it works with $ne but on my query sails model it always returns undefined?
Example query:
Stream.findOne({thread: {$ne: null } }, function(err, st){
if(err) return err;
console.log("st", st);
});
How can I resolve this?
Use the .native() method:
Stream.native(function(err, collection) {
if (err) return res.serverError(err);
collection.find({
"thread": { "$ne": null }
}).toArray(function(err, st) {
if (err) return res.serverError(err);
console.log("st", st);
return res.ok(st);
});
});
Or the .where() method:
var myQuery = Stream.find();
myQuery.where({'thread':{ '$ne': null}});
myQuery.exec(function callBack(err, results){
console.log(results)
});