Reputation: 45
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.
Upvotes: 2
Views: 189
Reputation: 46451
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]
Upvotes: 1