2

I have a document in my collection:

  {
    "_id" : ObjectId("5b8aaaebf57de10e080c9151"),
    "user_email" : "[email protected]",
    "platforms_budget" : [ 
        {
            "_id" : ObjectId("5b8aaaebf57de10e080c9154"),
            "platform_id" : "f_01",
            "platform_name" : "Facebook"
        }, 
        {
            "_id" : ObjectId("5b8aaaebf57de10e080c9153"),
            "platform_id" : "i_01",
            "platform_name" : "Instagram"
        }, 
        {
            "_id" : ObjectId("5b8aaaebf57de10e080c9152"),
            "platform_id" : "f_02",
            "platform_name" : "Facebook_Adds"

        }
    ],
    "__v" : 0
    }

I want to find specific user by "user_email" and get only the length of the relevant "platform_budget" array.

My function is like this:

var BudgetSchema = require('../models/Budget');

  router.post('/temp', async function (req, res) {
  var length = await BudgetSchema.aggregate(
    [{ $match: { user_email: "[email protected]" } },
    { $project: { "count": { $size: '$platforms_budget' } } }])

  console.log(length);
})

The output that I get is:

[ { _id: 5b8aaaebf57de10e080c9151, count: 3 } ]

But I want to get only the size as a number, like this: 3.

The output that I want to get is:

 3

I understand that I can use the $slice operator, but I can't figure how to use it in the right way. Any ideas? Thanks.

0

1 Answer 1

1

Your aggregation should be like this

BudgetSchema.aggregate([
  { "$match": { "user_email": "[email protected]" } },
  { "$project": { "count": { "$size": "$platforms_budget" }}}
])

Output

[ { _id: "5b8aaaebf57de10e080c9151", count: 3 } ]

If you want it as an array value

const budget = (await BudgetSchema.aggregate([
  { "$match": { "user_email": "[email protected]" } },
  { "$project": { "count": { "$size": "$platforms_budget" }}}
])).map(({ count }) => count)

Output

[3]
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, thank you. I want to cut the output and accept only "3" or extract it from the responce in any other way.
I updated my question. I hope that is more clear now.
your output is not a valid json... MongoDB itself won't return anything other than a BSON Document, and a simple "string or integer" is NOT a BSON Document.
Yes! Thank you very much for your help.

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.