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

Append item to MongoDB document array in PyMongo without re-insertion

You don’t need to use to retrieve the document first just use the .update method with the $push operator. def update_tags(ref, new_tag): coll.update({‘ref’: ref}, {‘$push’: {‘tags’: new_tag}}) Since update is deprecated you should use the find_one_and_update or the update_one method if you are using pymongo 2.9 or newer

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 nested array query

After running some queries, I came to the conclusion that $in doesn’t work for an array of arrays. You can use $elemMatch instead and it’ll work, but it is frustrating that MongoDB’s documentation doesn’t warn about it. I created this document: { “_id”: “51cb12857124a215940cf2d4”, “level1”: [ [ “item00”, “item01” ], [ “item10”, “item11” ] ], … 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