3

I have an array of distinct items -

search = alluk.distinct('Object of search')

I am looking to do a count for each item. Currently I am doing them manually like so -

alluk.find({'Object of search':'Offensive weapons'}).count()

Question

Is it possible to loop through the search array counting for each item in turn?

I have tried -

alluk.find({'Object of search':{'$in': search}}).count()

However this isn't exactly what I am after.

SOLUTION -

for item in alluk.aggregate([
  { '$match': { 'Object of search': { '$in': objectofsearch }}},
  { '$group': {
    '_id': '$Object of search',
    'count': { '$sum': 1 }
  }}
]):
    print(item)

1 Answer 1

2

You can use $group aggregation to count the number of distinct counts

alluk.aggregate([
  { '$match': { 'Object of search': { '$in': search }}},
  { '$group': {
    '_id': '$Object of search',
    'count': { '$sum': 1 }
  }}
])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks final solution added

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.