$project in $lookup mongodb

You can use $lookup 3.6 syntax to $project the fields inside the $lookup pipeline User.aggregate([ { “$lookup”: { “from”: “schedules”, “let”: { “id”: “$_id.phone” }, “pipeline”: [ { “$match”: { “$expr”: { “$eq”: [“$customer.phone”, “$$id”] }}}, { “$project”: { “scheduleStart”: 1, “scheduleEnd”: 1 }} ], “as”: “user_detail” }} ])

Loop through all Mongo collections and execute query

There is the db.getCollectionNames() helper method that does this for you. You can then implement your code: db.getCollectionNames().forEach(function(collname) { // find the last item in a collection var last_element = db[collname].find().sort({_id:-1}).limit(1); // check that it’s not empty if (last_element.hasNext()) { // print its timestamp printjson(last_element.next()._id.getTimestamp()); } }) You probably also want a .hasNext() check in … Read more

MongoDB: find and findOne with nested array filtering

I’ll TL;DR since this turned out to be a hell of a ride. I’ve tried $elemMatch, I’ve tried $redact (also with $$CURRENT and $$ROOT), I’ve tried $map, I’ve tried the aggregation framework, I’ve tried $project. You can read all about it here: https://www.devsbedevin.net/mongodb-find-findone-with-nested-array-filtering-finally/ TL;DR The solution seems to be to use the aggregation framework to … Read more

Count array elements that matches condition

You need to use $filter aggregation to filter out the external origin and internal origin along with the $size aggregation to calculate the length of the arrays. Something like this db.collection.aggregate([ { “$addFields”: { “internalUsersCount”: { “$size”: { “$filter”: { “input”: “$participants”, “as”: “part”, “cond”: { “$eq”: [“$$part.origin”, “internal”]} } } }, “externalUsersCount”: { “$size”: … Read more