How to deal with the timezone issue when storing dates in utc using mongod?

Aside from the SERVER-6310 mentioned by Matt Johnson, one other workaround is to use the $project operator to add or subtract from the UTC time zone to “shift the time” into the correct local zone. Turns out you can add or subtract time in milliseconds. For example, assuming I have a Date field called orderTime. … Read more

Geospatial $near within current document field value

Yes it’s possible. You just use $geoNear instead. Beware the catches and read carefully. Presuming that your intent to is to store a field such as “travelDistance” to indicate on the document that any such searches must be “within” that supplied distance from the queried point to be valid. Then we simply query and evaluate … Read more

How to access overall document count during arithmetic aggregation expression

One way to do it is use $setWindowFields: db.collection.aggregate([ { $setWindowFields: { output: { totalCount: {$count: {}} } } }, { $unwind: “$items” }, { $group: { _id: “$items.defindex”, count: {$sum: 1}, totalCount: {$first: “$totalCount”} } }, { $project: { count: 1, usage: {$divide: [“$count”, “$totalCount”] } } }, {$sort: {count: -1}} ]) As you … Read more

Performing case-statement in mongodb aggregation framework

what corresponds to the “case” SQL statement in the aggregation framework, is the $cond operator (see manual). $cond statements can be nested to simulate “when-then” and “else”, but I have chosen another approach, because it is easier to read (and to generate, see below): I’ll use the $concat operator to write the range string, which … Read more

Search on multiple collections in MongoDB

This answer is outdated. Since version 3.2, MongoDB has limited support for left outer joins with the $lookup aggregation operator MongoDB does not do queries which span multiple collections – period. When you need to join data from multiple collections, you have to do it on the application level by doing multiple queries. Query collection … Read more

MongoDB: Calculate dwell time between every status value change

Check if this solution meets your requirements. Explanation We join over the same collection. So for each item i we take item i+1. This method gives us where presenceStatus has been changed. We filter documenti i+1 pairs where presenceStatus is 0 – 1 or 1 – 0. We group them into single data array. Now … Read more

MongoDB: how to parse date in 3.6 mongoDb version?

Use $dateToParts and its counterpart $dateFromParts Here is an updated Playground What it does is basically break the date into its parts: { $project: { dateHour: { $dateToParts: { date: “$updatedAt” } } } } would produce: { “dateHour”: { “day”: 19, “hour”: 18, “millisecond”: 0, “minute”: 21, “month”: 3, “second”: 5, “year”: 2020 } … Read more

tech