find multiple document ascending with limit 1 mongoose - node.js

I am new to Mongodb.
This is what i have tried
var fdevices = mongoose.model('fdevices', dataModelSchema);
var DPMPow = fdevices.findOne({ "Data": { $regex: /DPMPow_P01/i }
}).sort({ field: 'asc', _id: -1 });
var DPMAmp = fdevices.findOne({ "Data": { $regex: /DPMAmp_P01/i }
}).sort({ field: 'asc', _id: -1 });
var DPMkWh = fdevices.findOne({ "Data": { $regex: /DPMkWh_P01/i }
}).sort({ field: 'asc', _id: -1 });
var MxPeak = fdevices.findOne({ "Data": { $regex: /MxPeak_P01/i }
}).sort({ field: 'asc', _id: -1 });
var MPPeak = fdevices.findOne({ "Data": { $regex: /MPPeak_P01/i }
}).sort({ field: 'asc', _id: -1 });
function getReady() {
async.series([
function (callback) {
DPMPow.exec(function (err, res) {
callback(null, res);
})
},
function (callback) {
DPMAmp.exec(function (err, res) {
callback(null, res);
});
},
function (callback) {
DPMkWh.exec(function (err, res) {
callback(null, res);
})
},
function (callback) {
MxPeak.exec(function (err, res) {
callback(null, res);
})
}, function (callback) {
MPPeak.exec(function (err, res) {
callback(null, res);
}) ], function (error, results) {
console.log(results);
}
);
}
above method works for me but its very slow. is there a way i can design single query and get same result instead of queering data one by one.
In my collection i have single field called "Data" and my collection contains more than a one million document.

var fdevices = mongoose.model('fdevices', dataModelSchema);
var DPMPow = fdevices.find({
$or: [{
"Data": { $regex: /DPMPow/i }
}, {
"Data": { $regex: /DPMAmp/i }
}, {
"Data": { $regex: /DPMkWh/i }
}, {
"Data": { $regex: /MxPeak/i }
}, {
"Data": { $regex: /MPPeak/i }
}]
}).sort({ field: 'asc', _id: -1 });
DPMPow.exec(function(err, res) {
//Now travese thru all the records, when ever you find the unique pattren of
//data remove all the instances of that particular pattren
});

Related

How to project a new boolean field in Mongoose if another property is listed in existing array?

Consider the query in Mongoose :
let StudentCodes = .... // getting this from somewhere
await Students.aggregate(
[
{
$project: {
StudentCODE: "$StudentCODE",
StudName: "$StudName",
StudProfileDesc: "$StudProfileDesc",
IsReviewed: {
$cond: [{ $eq: [StudentCodes, "$StudentCODE"] }, 1, 0]
}
}
}
],
function(err, results) {
if (err) {
console.log(err);
}
console.log(results);
return res.status(200).json(results);
}
);
How can We project IsReviewed as true or false if the property StudentCODE exists in the array StudentCodes ?
Try as below, you can use $in in $cond to do that :
let StudentCodes = .... // getting this from somewhere
await Students.aggregate(
[
{
$project: {
StudentCODE: "$StudentCODE",
StudName: "$StudName",
StudProfileDesc: "$StudProfileDesc",
IsReviewed: {
$cond: [{ $in: ["$StudentCODE", StudentCodes] }, true, false]
}
}
}
],
function (err, results) {
if (err) {
console.log(err);
}
console.log(results);
return res.status(200).json(results);
}
);

Using regex to Retrieve multiple data from Mongodb

I am new to Mongodb
Here is what i have tried. however this method worked for me but its way slow.
Is it possible to design single query to get all this data. instead of querying one by one.
var Schema = mongoose.Schema;// Schema
var dataModelSchema = new Schema({
data: String,
});
var fdevices = mongoose.model('fdevices', dataModelSchema);
var DPMPow = fdevices.findOne({ "Data": { $regex: /DPMPow_P01/i } }).sort({
field: 'asc', _id: -1 }); //Active Power
var DPMAmp = fdevices.findOne({ "Data": { $regex: /DPMAmp_P01/i } }).sort({
field: 'asc', _id: -1 });//Total Current
var DPMkWh = fdevices.findOne({ "Data": { $regex: /DPMkWh_P01/i } }).sort({
field: 'asc', _id: -1 });//Consumption
var MxPeak = fdevices.findOne({ "Data": { $regex: /MxPeak_P01/i } }).sort({
field: 'asc', _id: -1 });//Max Demand Peak
var MPPeak = fdevices.findOne({ "Data": { $regex: /MPPeak_P01/i } }).sort({
field: 'asc', _id: -1 });//Max Demand Partial
async.series([
function (callback) {
DPMPow.exec(function (err, res) {
callback(null, res);
})
},
function (callback) {
DPMAmp.exec(function (err, res) {
callback(null, res);
});
},
function (callback) {
DPMkWh.exec(function (err, res) {
callback(null, res);
})
},
function (callback) {
MxPeak.exec(function (err, res) {
callback(null, res);
})
}, function (callback) {
MPPeak.exec(function (err, res) {
callback(null, res);
})
//chiller1
}
], function (err, results) {
console.log(results);
});
this is how my data looks like in database. in collection got only one field which name as 'Data' this field receives multiple sensors data in every one hour.
{ _id: 5b2118c4ae33249711a498a6,
Data: '13-06-2018 20:14:46 DPMPow_P01_04_ 699.15 ',
__v: 0 },
{ _id: 5b2118c4ae35439711a498a6,
Data: '13-06-2018 20:14:46 MPPeak_P01_04_ 699.15 ',
__v: 0 },
{ _id: 5b23428c4ae32989711a498a6,
Data: '13-06-2018 20:14:46 DPMAmp_P01_04_ 699.15 ',
__v: 0 },
{ _id: 5b21234c4ae32989711a498a6,
Data: '13-06-2018 20:14:46 DPMkWh_P01_04_ 699.15 ',
__v: 0 },
{ _id: 5b2118c4ae34989711a598a6,
Data: '13-06-2018 20:14:46 MxPeak_P01_04_ 699.15 ',
__v: 0 }
You can try below RegEx in find query
let data = fdevices.find({ "Data": { $regex: /(DPMPow)|(MPPeak)|(DPMAmp)|(DPMkWh)|
(MxPeak)/gm } }).sort({ field: 'asc', _id: -1 });

Node.js "ignore" $sort in a collection.aggregate query

This could be a dumb question, but I'm desperate already! I need to do this query:
db.clients.aggregate(
{
$group: {
_id: '$enterprise',
lodging_days: { $sum: '$lodging_days' }
}
},
{
$sort : {
lodging_days: -1
}
})
And, if I copy this on the mongo bash, I returned this: Bash Return
(Sorry, I can't upload images yet)
JUST LIKE I WANT!
But, when I put the query on node:
router.get('/query', function(req, res){
var db = req.db;
var clients=db.get('clients');
clients.aggregate(
{
$group: {
_id: '$enterprise',
lodging_days: { $sum: '$lodging_days' }
}
},
{
$sort: {
'lodging_days': -1
}
},
function(e, data){
res.json(data);
}
);
});
This "ignore" the $sort and return me this: Interface Return
Now, my question are... Why!? And what can I make to fix it?
Your need to wrap your pipeline into array.
router.get('/query', function(req, res){
var db = req.db;
var clients=db.get('clients');
clients.aggregate([
{
$group: {
_id: '$enterprise',
lodging_days: { $sum: '$lodging_days' }
}
},
{
$sort: {
'lodging_days': -1
}
}],
function(e, data){
res.json(data);
}
);
});

Node JS Mongoose PULL query

I find many great answers here on SO like this answer an this. But i can not get it to work...
I tried ObjectId("55cf816559d2fc8d0e6c14a8") in the query where the id is.
This query works when robotmongo run it:
db.getCollection('events').update(
{ "_id": ObjectId("55cf816559d2fc8d0e6c14a8") },
{ "$pull": { "workers" : { "_id": ObjectId("55cf89ac7cba1d0a10ca86c7")}}},
false,
true
)
Side note, what is the false,true for?
Here is my current code
event.update(
{'_id': "55cf816559d2fc8d0e6c14a8"},
{ "$pull": { "workers" : {_id: "55cf89ac7cba1d0a10ca86c7"}}},
function(err, result) {
console.log(err);
console.log(result);
}
);
I do not get any errors and the result is equal to 1.
Works for me. You must be doing something differently and incorrectly:
var async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var workerSchema = new Schema({
name: String
});
var eventSchema = new Schema({
name: String,
workers: [workerSchema]
});
var Event = mongoose.model( 'Event', eventSchema );
async.series(
[
function(callback) {
Event.remove({},function(err) {
callback(err);
});
},
function(callback) {
var event = new Event({
_id: "55cf816559d2fc8d0e6c14a8",
name: "Great thing"
});
event.workers.push({
_id: "55cf89ac7cba1d0a10ca86c7",
name: "Worker1"
});
event.save(function(err,event) {
console.log(event);
callback(err);
});
},
function(callback) {
Event.findOneAndUpdate(
{ "_id": "55cf816559d2fc8d0e6c14a8" },
{ "$pull": { "workers": { "_id": "55cf89ac7cba1d0a10ca86c7" } } },
{ "new": true },
function(err,event) {
console.log(event)
callback(err);
}
);
}
],
function(err) {
if (err) throw err;
mongoose.disconnect();
}
);
With the expected output:
{ __v: 0,
_id: 55cf816559d2fc8d0e6c14a8,
name: 'Great thing',
workers: [ { _id: 55cf89ac7cba1d0a10ca86c7, name: 'Worker1' } ] }
{ _id: 55cf816559d2fc8d0e6c14a8,
name: 'Great thing',
__v: 0,
workers: [] }

What am I doing wrong trying to make this run with meteor?

I am trying to adapt the full text search made here to work with meteor. I exported the mongodb url to one running 2.6.1. to make full text search compatible but I am getting these errors server/search.js:2:15: Unexpected token .andserver/search.js:42:7: Unexpected token ). What am I missing?
server.js
Meteor.methods({
Meteor.ensureIndex("Posts", {
smaintext: "text"
}, function(err, indexname) {
assert.equal(null, err);
});
)
};
Meteor.methods({
feedupdate: function(req) {
Posts.find({
"$text": {
"$search": req
}
}, {
smaintext: 1,
submitted: 1,
_id: 1,
Posts: {
$meta: "Posts"
}
}, {
sort: {
textScore: {
$meta: "posts"
}
}
}).toArray(function(err, items) {
for (e=0;e<101;e++) {
Meteor.users.update({
"_id": this.userId
}, {
"$addToSet": {
"profile.search": item[e]._id
}
});
}
})
}
)
};
This is wrong definition of method
Meteor.methods({
Meteor.ensureIndex("Posts", {
smaintext: "text"
}, function(err, indexname) {
assert.equal(null, err);
});
)
};
you must specify a method name ( http://docs.meteor.com/#/basic/Meteor-methods )
So it will be something like this
Meteor.methods({
myMethodName : function() { Meteor.ensureIndex("Posts", {
smaintext: "text"
}, function(err, indexname) {
assert.equal(null, err);
});
}
});
in second method there is a semicron and parenthise problem.
Correct version is
Meteor.methods({
feedupdate: function(req) {
Posts.find({
"$text": {
"$search": req
}
}, {
smaintext: 1,
submitted: 1,
_id: 1,
Posts: {
$meta: "Posts"
}
}, {
sort: {
textScore: {
$meta: "posts"
}
}
}).toArray(function(err, items) {
for (e=0;e<101;e++) {
Meteor.users.update({
"_id": this.userId
}, {
"$addToSet": {
"profile.search": item[e]._id
}
});
}
});
}
});

Resources