0

Say, I have following documents:

{name: 'A', fav_fruits: ['apple', 'mango', 'orange'], 'type':'test'}
{name: 'B', fav_fruits: ['apple', 'orange'], 'type':'test'}
{name: 'C', fav_fruits: ['cherry'], 'type':'test'}

I am trying to query to find the total count of fav_fruits field on overall documents returned by :

cursor = db.collection.find({'type': 'test'})

I am expecting output like:

cursor.count() = 3 // Getting

Without much idea of aggregate, can mongodb aggregation framework help me achieve this in any way:

1. sum up the lengths of all 'fav_fruits' field: 6 

and/or

2. unique 'fav_fruit' field values = ['apple', 'mango', 'orange', 'cherry']

3 Answers 3

1

You need to $project your document after the $match stage and use the $size operator which return the number of items in each array. Then in the $group stage you use the $sum accumulator operator to return the total count.

db.collection.aggregate([
    { "$match": { "type": "test" } },
    { "$project": { "count": { "$size": "$fav_fruits" } } }, 
    { "$group": { "_id": null, "total": { "$sum": "$count" } } }
])

Which returns:

{ "_id" : null, "total" : 6 }

To get unique fav_fruits simply use .distinct()

> db.collection.distinct("fav_fruits", { "type": "test" } )
[ "apple", "mango", "orange", "cherry" ]
Sign up to request clarification or add additional context in comments.

Comments

0

Do this to get just the number of fruits in the fav_fruits array:

db.fruits.aggregate([
    { $match: { type: 'test' } },
    { $unwind: "$fav_fruits" },
    { $group: { _id: "$type", count: { $sum: 1 } } }
]);

This will return the total number of fruits.

But if you want to get the array of unique fav_fruits along with the total number of elements in the fav_fruits field of each document, do this:

db.fruits.aggregate([
    { $match: { type: 'test' } },
    { $unwind: "$fav_fruits" },
    { $group: { _id: "$type", count: { $sum: 1 }, fav_fruits: { $addToSet: "$fav_fruits" } } }
])

Comments

0

You can try this. It may helpful to you.

db.collection.aggregate([{ $match : { type: "test" } }, {$group : { _id : null, count:{$sum:1} } }])

Comments

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.