$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” }} ])

MongoDB to Use Sharding with $lookup Aggregation Operator

As the docs you quote indicate, you can’t use $lookup on a sharded collection. So the best practice workaround is to perform the lookup yourself in a separate query. Perform your aggregate query. Pull the “localField” values from your query results into an array, possibly using Array#map. Perform a find query against the “from” collection, … 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

Find documents whose array field contains at least n elements of a given array

Let say we have the following documents in our collection: { “_id” : ObjectId(“5759658e654456bf4a014d01”), “a” : [ 1, 3, 9, 2, 9, 0 ] } { “_id” : ObjectId(“5759658e654456bf4a014d02”), “a” : [ 0, 8, 1 ] } { “_id” : ObjectId(“5759658e654456bf4a014d03”), “a” : [ 0, 8, 432, 9, 34, -3 ] } { “_id” : … Read more