Getting a document with the minimum or maximum value in a field MongoDB - node.js

How do you get a document with the minimum or maximum value in a field in MongoDB?
Similar to the MIN() or MAX() functions in MySQL, but using the NodeJS MongoDB driver. Any ideas?

you can try to use asc, desc sort with limit(1)
db.col.insert({val: 9});
db.col.insert({val: 4});
db.col.insert({val: 20});
db.col.find();
{ "_id" : ObjectId("511bf79298bb011e3a33747d"), "val" : 9 }
{ "_id" : ObjectId("511bf79698bb011e3a33747e"), "val" : 4 }
{ "_id" : ObjectId("511bf79d98bb011e3a33747f"), "val" : 20 }
db.col.find().sort({val: 1}).limit(1); //min
{ "_id" : ObjectId("511bf79698bb011e3a33747e"), "val" : 4 }
db.col.find().sort({val: -1}).limit(1); //max
{ "_id" : ObjectId("511bf79d98bb011e3a33747f"), "val" : 20 }

Related

$add,$subtract aggregation-framework in mongodb

Hi i am mentioning the sample data
///collection - test////
{
"_id" : {
"date" : ISODate("2020-02-11T17:00:00Z"),
"userId" : ObjectId("5e43e5cdc11f750864f46820"),
"adminId" : ObjectId("5e43de778b57693cd46859eb")
},
"outstanding" : 212.39999999999998,
"totalBill" : 342.4,
"totalPayment" : 130
}
{
"_id" : {
"date" : ISODate("2020-02-11T17:00:00Z"),
"userId" : ObjectId("5e43e73169fe1e3fc07eb7c5"),
"adminId" : ObjectId("5e43de778b57693cd46859eb")
},
"outstanding" : 797.8399999999999,
"totalBill" : 797.8399999999999,
"totalPayment" : 0
}
I need to structure a query which does following things-
I need to calculate the actualOutstanding:[(totalBill+outstanding)-totalPayment],
I need to save this actualOutstanding in the same collection & in the same document according to {"_id" : {"date","userId", "adminId" }}
NOTE: userId is different in both the documents.
Introduced in Mongo version 4.2+ pipelined updates, meaning we can now use aggregate expressions to update documents.
db.collection.updateOne(
{
"adminId" : ObjectId("5e43de778b57693cd46859eb")
'_id."userId" : ObjectId("5e43e73169fe1e3fc07eb7c5"),
'_id.date': ISODate("2020-02-11T18:30:00Z"),
},
[
{ '$set': {
actualOutstanding: {
$subtract:[ {$add: ['$totalBill','$outstanding']},'$totalPayment']
}
} }
]);
For any other Mongo version you have to split it into 2 actions, first query and calculate then update the document with the calculation.

Query an array in MongoDB

I have this collection in MongoDB:
{
"_id" : ObjectId("5df013b10a88910018267a89"),
"StockNo" : "33598",
"Description" : "some description",
"detections" : [
{
"lastDetectedOn" : ISODate("2020-01-29T04:36:41.191+0000"),
"lastDetectedBy" : "comp-t",
"_id" : ObjectId("5e3135f68c9e930017de8aec")
},
{
"lastDetectedOn" : ISODate("2019-12-21T18:12:06.571+0000"),
"lastDetectedBy" : "comp-n",
"_id" : ObjectId("5e3135f68c9e930017de8ae9")
},
{
"lastDetectedOn" : ISODate("2020-01-29T07:36:06.910+0000"),
"lastDetectedBy" : "comp-a",
"_id" : ObjectId("5e3135f68c9e930017de8ae7")
}
],
"createdAt" : ISODate("2019-12-10T21:52:49.788+0000"),
"updatedAt" : ISODate("2020-01-29T07:36:22.950+0000"),
"__v" : NumberInt(0)
}
I want to search by StockNo and get the name of the computer that last detected it (lastDetectedBy) only if lastDetectedOn was in the last 5 minutes with Mongoose in node.js with Express.
I also have this collection:
{
"_id" : ObjectId("5df113b10d35670018267a89"),
"InvoiceNo" : "1",
"InvoiceDate" : ISODate("2020-01-14T02:18:11.196+0000"),
"InvoiceContact : "",
"isActive" : true
},
{
"_id" : ObjectId("5df013c90a88910018267a8a"),
"InvoiceNo" : "2",
"InvoiceDate" : ISODate("2020-01-14T02:18:44.279+0000"),
"InvoiceContact : "Bob Smith",
"isActive" : true
},
{
"_id" : ObjectId("5e3096bb8c9e930017dc6e20"),
"InvoiceNo" : "3",
"InvoiceDate" : ISODate("2020-01-14T02:19:50.155+0000"),
"InvoiceContact : "",
"isActive" : true
}
And I want to update all the documents with empty InvoiceContact which has been issued in the last 30 seconds (or any date range between now and sometime in the past) with isActive equals true to isActive equals false. So for example, the first record has been issued in the last 30 seconds without InvoiceContact and isActive is true so this must be updated but the next two records will remain untouched for different reasons, the second record has InvoiceContact and the third record is out of range.
First Part
var mins5 = new Date(ISODate() - 1000* 60 * 5 )
db.getCollection('user').find({$and:[
{ "StockNo":"33598"},
{"detections.lastDetectedOn" : { $gte : mins5 }}
]})
.map(function(list){
var results = [];
list.detections.forEach(function (detections){
if(detections.lastDetectedOn > mins5){
results.push(detections.lastDetectedBy);
}
})
return results;
});
Second Part could be solved by a similar query using update instead of find.

$and operator does not return any result in mongodb?

Hi EveryOne I'm beginner in MongoDB.I want to return some documents in mongodb. I'm using NodeJS. I have multiple documents in collections.In my case I want to return documents which have column called make both 2002 and 2008 and I need return columns only name.Thanks in advance....
My code:
db.collection('cars').find(
{$and:[ {$in:{make:{2002,2008}} ]}
,{name:1,_id:0},(err,doc)=>{
if(err){
throw err;
}
else{
console.log(doc);
}});
I have collections in my db:
/* 1 */
{
"_id" : ObjectId("5cddda829719b0234ccef10d"),
"name" : "Posche",
"make" : 2002,
"price" : 2300000
}
/* 2 */
{
"_id" : ObjectId("5cdee01d1f92122b785874ba"),
"name" : "Audi",
"make" : 2002,
"price" : 2300000
}
/* 3 */
{
"_id" : ObjectId("5cdee01d1f92122b785874bb"),
"name" : "BMW",
"make" : 2003,
"price" : 2000000
}
/* 4 */
{
"_id" : ObjectId("5cdee01d1f92122b785874bc"),
"name" : "Toyoto",
"make" : 2005,
"price" : 1500000
}
/* 5 */
{
"_id" : ObjectId("5cdee3e71f0e0ab8a16cb2c8"),
"make" : 2008,
"name" : "Volvo",
"price" : 59862
}
My Expected output:
[{"name" : "Posche"},
{"name" : "Audi"},
{"name" : "volvo"}]
The query you seem to be looking for is:
db.collection('cars').find({ make: {$in:[2002,2008]},{name:1,_id:0}, ... rest of your code
This will return documents which make matches any of those two years.

MongoDB query with embedded document in array (3 levels)

I had this data on my MongoDB database and I would like to get only the second array about blades.
{
"_id" : ObjectId("..."),
"name" : "Westereems",
"country" : "Netherlands",
"turbines" : [
{
"turbine_id" : ObjectId("..."),
"blades" : [
{
"blade_id" : ObjectId("..."),
"position" : 2,
"size" : 50,
}
]
}
]
}
I only want one return with blade_id, position and size. I tried this query and I didn't have the expectable result:
db.collection("windfarms").find({"turbines.blades.blade_id" : ObjectId("...")}, {"turbines.blades.$" : 1, "_id" : 0})
Regards,
You can use this query, it's not an optimal query for large array's items but if you have only above items then you can use it.
you can also go with aggregation to make it more optimal.
db.collection("windfarms").find({"turbines.blades.blade_id" : ObjectId("...")}, {"turbines.blades.blade_id":1,"turbines.blades.position":1,"turbines.blades.size":1,"_id":0})

How to query data from mongodb collection by just the first 3 numbers

I have a collection in my mongodb that is called pnumber and looks like this when I do db.pnumber.find() mongo shell
{ "_id" : ObjectId("57696e03b9c614e1143c759e"), "pnumber" : NumberLong("5037816575") }
{ "_id" : ObjectId("57696e03b9c614e1143c759f"), "pnumber" : NumberLong("5087368074") }
{ "_id" : ObjectId("57696e03b9c614e1143c75a0"), "pnumber" : NumberLong("8055019263") }
{ "_id" : ObjectId("57696e03b9c614e1143c75a1"), "pnumber" : NumberLong("2153334813") }
{ "_id" : ObjectId("57696e03b9c614e1143c75a2"), "pnumber" : NumberLong("5592842086") }
{ "_id" : ObjectId("57696e03b9c614e1143c75a3"), "pnumber" : NumberLong("4356696916") }
{ "_id" : ObjectId("57696e03b9c614e1143c75a4"), "pnumber" : NumberLong("9545935012") }
{ "_id" : ObjectId("57696e03b9c614e1143c75a5"), "pnumber" : NumberLong("8083661362") }
{ "_id" : ObjectId("57696e03b9c614e1143c75a6"), "pnumber" : NumberLong("6065240853") }
{ "_id" : ObjectId("57696e03b9c614e1143c75a7"), "pnumber" : NumberLong("4236768328") }
{ "_id" : ObjectId("57696e03b9c614e1143c75a8"), "pnumber" : NumberLong("9705354839") }
I am using a mean stack application that is connected to this database through mongoose.
I would like to have an input field with a search button that when a user enters the area code that a list pops up from the collection of all the entry's that match that area code and have a download button that creates a csv with all of those entries.
I have:
var csv = require('express-csv');
in my app.js file.
Any info would be much appreciated.
db.pnumber.find( { pnumber: /^123/ } )
this results with all response that start with the value 123.
if you tie the form with this, the response should be the results you are looking for.
if you would like to match strings, use $regex operator
db.getCollection('blah').find({'phoneNumber':{'$regex': /^phoneNumber/}})
if you would like to match numbers, use $where operator.
db.getCollection('blah').find({$where: "/^970*/.test(this.phoneNumber)"})

Resources