1

So I have my pymongo cursor and very plain loop to get total sum. I need to fetch that value, also I am very new to Mongo and my approach might be not the best practice.

cursor = db.reportsColl.aggregate([
        {"$unwind": "$conditions"},
        {"$group": {"_id": "$_id", "sum": { "$sum": 1}}}])


x = 0
for result in cursor:
    x+= result['sum']
print(x)

I am trying to use lambda expression here, but I feel that I've kinda lost.

total = [(lambda x: x+result['sum'])(x) for _ in cursor]

Any ideas?

5
  • 2
    Did you mean something like total = sum(result['sum'] for result in cursor) Commented Aug 27, 2017 at 12:57
  • @AChampion definitely! How I couldn't do it in the 1st place... Thanks. Commented Aug 27, 2017 at 12:59
  • 1
    @AliceJarmusch slightly confused as to what you're doing here... can't you modify your query and have mongo do it rather than post-processing in Python? Although, I'm not sure if you're trying to get the number of groups, or something else... Commented Aug 27, 2017 at 13:08
  • @JonClements if you can suggest how can I do it in mongo, I will be happy. Had never worked with it before, and I just need to grab some aggregated data for the further calculations. Commented Aug 27, 2017 at 13:10
  • 1
    @Alice that's what I'm wondering... perhaps the real question you should be asking is "How do I get the following using a mongo query" and describing what the aggregation you want is, your attempt (like above) and some sample data etc... Commented Aug 27, 2017 at 13:11

2 Answers 2

2

You are building a list of incomplete sums, and that's a waste. Don't use a list comprehension for the side effects.

You don't even need to do this. Use the sum() function with a generator expression instead:

total = sum(result['sum'] for result in cursor)
Sign up to request clarification or add additional context in comments.

Comments

0

You only want to do is SUM.

So, you can try to do follow this:

In [9]: sum([1, 2, 3])
Out[9]: 6`

So, by this way, your code can be like:

total = sum([result['sum'] for result in cursor])

1 Comment

Drop the [...] brackets, there is no need to create a list first to sum the contents. Use a generator expression instead.

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.