1

I have collections Users and Numbers. Each number has AllocatedToUserId (ObjectId) field, User can have many numbers. How can I in single query return User with NumbersCount? I wrote this

db.getCollection('Users').aggregate([
      {'$lookup': {from: "Numbers",
                   localField: "_id",
                   foreignField: "AllocatedToUserId",
                   as: "Numbers"}
      },{ '$project' : {_id:0,
                       document: '$$ROOT',
                       count: {$size:'$Numbers'}}}
      ])

But with this code I got structure of response like that:

[{document, count},{document, count},{document, count}...]

Where each document has Numbers collection, and I'd like to have count inside document and without collection of numbers. Is it possible? Thanks!

1 Answer 1

1

You don't necessarily need to project another field with the $$ROOT system variable, just project the fields from the users schema. The following example assumes you have a user with the schema:

Exmple Users Schema

{
    "_id": ObjectId
    "firstName": String,
    "lastName": String,
    "age": Integer,
    "location": String
}

Pipeline

db.getCollection('Users').aggregate([
    {
        "$lookup": {
            "from": "Numbers",
            "localField": "_id",
            "foreignField": "AllocatedToUserId",
            "as": "Numbers"
        }
    },
    {   
        "$project": {
            "firstName": 1,
            "lastName": 1,
            "age": 1,
            "location": 1,
            "Numbers": 0,
            "count": { "$size": "$Numbers" } 
        }
    }
])
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! Yep, probably that's a solution, but my user schema has ~25 fields. That's why I used $$ROOT.
With $$ROOT you were still going to have another $project pipeline to flatten the document embedded document
So.. That's mean that's, probably, best solution?
Unless if it's a strict requirement to have a flattened schema as a result I'm afraid you may have to $project every field otherwise the $$ROOT is a better solution since you don't have to explicitly project the fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.