C++ and count distinct

108 views
Skip to first unread message

Jeff Abrahamson

unread,
Dec 9, 2017, 11:57:51 AM12/9/17
to mongodb-user
In the mongo shell I can find unique field values thus:

    > db.email_events.distinct('sg_message_id', {'campaign_id':
'22'}).length
    2629
    >

In C++ I can do it thus, but with a transfer of all unique values from
the server:

    bsoncxx::string::view_or_value field_name = "sg_message_id";
    bsoncxx::builder::basic::document doc;
    doc.append(kvp("campaign_id", "22"));
    mongocxx::cursor cursor = email_events.distinct(field_name, doc.view());
    int num = 0;
    for (auto doc : cursor) {
        // This loop will execute 2629 times (today).
        cout << bsoncxx::to_json(doc) << endl;
        ++num;
    }
    cout << num << endl;

Is there a way to query just the number as in the shell example?  Once I
have the cursor it's clearly too late.  The collection::distinct()
function does not want a count option, using the count function it's
unclear how to specify a field name for which I want distinct values. 
I've not found help in the examples, browsing the code, via google...

Thanks.

--

Jeff Abrahamson
+33 6 24 40 01 57
+44 7920 594 255

http://p27.eu/jeff/


Andrew Morrow

unread,
Dec 12, 2017, 11:09:56 AM12/12/17
to mongod...@googlegroups.com

Hi Jeff -

Looking at the unit test associated with the collection::distinct method, I'm surprised by the behavior you are observing. What I would expect to see would be that the loop would execute once, returning you one document. That document would contain a values array containing the distinct values, per this test:


Could you please run that test locally and see if it passes for you?

Also, I'd strongly suggest looking into using the aggregation features of the server instead of using group/distinct.

Thanks,
Andrew

P.S. It is also helpful if, when posting questions, you could provide the version of the driver you are using.



--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.

For other MongoDB technical support options, see: https://docs.mongodb.com/manual/support/
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user+unsubscribe@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/7db3d383-958b-b4de-1dbb-b84a1e41f1ed%40p27.eu.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages