How to get the latest and oldest record in mongoose.js (or just the timespan between them)
Mongoose 3.x is complaining about the []
parameter in your findOne
calls as the array format is no longer supported for the parameter that selects the fields to include.
Try this instead to find the newest:
Tweet.findOne({}, {}, { sort: { 'created_at' : -1 } }, function(err, post) {
console.log( post );
});
Change the -1
to a 1
to find the oldest.
But because you're not using any field selection, it's somewhat cleaner to chain a couple calls together:
Tweet.findOne().sort({created_at: -1}).exec(function(err, post) { ... });
Or even pass a string to sort
:
Tweet.findOne().sort('-created_at').exec(function(err, post) { ... });
Find two latest and oldest documents which containing specific field values
You can try aggregate()
,
$match
your conditions$facet
to separate results, first is latest and second is oldest$sort
bytimestamp
in descending order$group
byslaveId
and get $first document in latest and $last document in oldest- $limit` to get single document
const latestPGStats = await PGStat.aggregate([
{
$match: {
deviceId: { $in: deviceIds },
timestamp: { $lte: endTimestamp, $gte: startTimestamp }
}
},
{ $sort: { timestamp: -1 } },
{
$facet: {
latest: [
{
$group: {
_id: "$slaveId",
root: { $first: "$$ROOT" }
}
},
{ $limit: 1 }
],
oldest: [
{
$group: {
_id: "$slaveId",
root: { $last: "$$ROOT" }
}
},
{ $limit: 1 }
]
}
}
])
Mongoose: How to get latest collection data?
I found out my problem after searching Stackoverflow.
The problem was fixed by removing , { sort: { _id: -1 }, limit: 1 });
and adding .sort.({"_id": -1})
to the end of my closing brackets!
Thanks for trying to answer my problem guys!
Displaying only the most recent mongoose timestamp?
If you want to display the most recent updateAt after the table, assign it to a variable during the loop, and display it later. Assuming updateAt
is numeric, that might look like
<%= newest = Math.max(newest, environment.updatedAt) =>
If you want the most recent time to be displayed first, or in each row, one option is to find the newest with reduce like
<%= environments.reduce(function(a,v){return Math.max(a,v.updatedAt)},0) =>
Or you could sort the query by updateAt: -1
when retrieving the data so the newest is the first element.
Get X records from 24 hours ago Mongoose
You can use limit
and sort
functions along with find
const pricesnow = await Prices.find({
currency_id: {
$in: [], // replace with currency array
},
createdAt: { $gt: new Date(Date.now() - 86400000) },
})
.sort({ createdAt: -1 })
.limit(10);
In mongo how to get the current position of the record in the table with the total records for pagination?
you can try this module mongoose-paginate
here what i uses, for pagination,
var current = req.query.filter.current;
var limit = req.query.filter.limit;
console.log('params.query.filter.current',current);
var skip = Number(limit)*Number(current)-Number(limit);
console.log('skip::',skip);
Cours.find({'attributes.version.status': true}).skip(skip).limit(limit).sort({_id:'asc'}).exec(function (err, resulta) {
if (err) {
console.log('erreur trouverCours');
res.json({
protecteds: err
});
}
console.log('cours ::', resulta);
res.json({
"data": resulta
});
});
MongoDB: Get latest 10 items in different data model?
Question 1 : If you are saving articles and tweets into separate collections, you'll either have to do application-side joining or use $lookup
operator, which will not work if you have sharded collections. I tend to avoid operators that have that limitation.
Question 2 : I don't work with SQL, can't help you there.
Question 3 : Saving everything into a single collection will definitely fit MongoDB philosophy more. MongoDB should be fast at retrieving, although slower in inserts and updates. Doing either application-side joining or having to use $lookup
kind of throw its ability to embed documents out of the windows.
As for your data model, here's my take. I used java driver and I used to have a custom deserializer/serializer to handle the document to POJO mapping. I believe it's natively supported in Mongo Java Driver 3.5, not sure if it's there for Mongoose already. In any case, you may define a Model/Object that contains all fields in both models, it'll then serialize accordingly, regardless which type you're fetching from DB using method 2. The model will get a little messy as you add more fields though, so some clever naming might be necessary
Related Topics
How to Add Spaces to for Loop Output in JavaScript
Why Is React Webpack Production Build Showing Blank Page
Bootstrap Modal Only Showing Backdrop
How to Pass Checkbox State to Onclick Function in React
Does JavaScript Guarantee Object Property Order
Regex - Get All Characters After Last Slash in Url
Create Parent and Child Relationship Using Lodash
How to Add Disable Option or Default Option in Select Box
Expanding Only One Row When Button Clicked
Passing Variable from Button to Modal
How to Send a Http Delete Request from Browser
Vue.Js Refs Are Undefined, Even Though This.$Refs Shows Theyre There
Focus Next Input Once Reaching Maxlength Value
How to Remove a Parameter from a Url
How to Detect Chinese Character With Punctuation in Regex
Node Js - Function to Return Array of Objects Read from Sequelize Database
How to Format Material Datepicker Date Value to "Mm-Dd-Yyy" Format in Angular 6