RejectedSoftware Forums

Sign up

Mongo runCommand Bson

Using runCommand on a mongo db:

    auto qry = Bson([
        "distinct":Bson("stuff"),
        "key":Bson("site"),
        "query":Bson(parseJsonString("{}"))
    ]);               
    
    auto qry2 = serializeToBson(parseJsonString(`{
        "distinct":"stuff", 
        "key":"site", 
        "query":{}}
    `));
    
    writeln(db.runCommand(qry)); // doesn't work
    writeln(db.runCommand(qry2)); // works

The second query form works, but I need to be able to use the first form (qry). I would have thought the two bson queries should be the same. Does anybody know what is wrong here?

Re: Mongo runCommand Bson

On Tue, 18 Mar 2014 03:09:28 GMT, cal wrote:

Using runCommand on a mongo db:

    auto qry = Bson([
        "distinct":Bson("stuff"),
        "key":Bson("site"),
        "query":Bson(parseJsonString("{}"))
    ]);               
    
    auto qry2 = serializeToBson(parseJsonString(`{
        "distinct":"stuff", 
        "key":"site", 
        "query":{}}
    `));
    
    writeln(db.runCommand(qry)); // doesn't work
    writeln(db.runCommand(qry2)); // works

The second query form works, but I need to be able to use the first form (qry). I would have thought the two bson queries should be the same. Does anybody know what is wrong here?

I think the issue here might be that the fields end up in a different order and MongoDB, although it arguably shouldn't, expects the "distinct" field to go first. This means, due to D's unordered AAs, that the only safe way to construct such a query is either going field-by-field, or using a struct:

Bson query;
query["distinct"] = "stuff";
query["key"] = "site";
query["query"] = Bson.emptyObject;
db.runCommand(query)

// or

struct DistinctQuery {
  string distinct;
  string key;
  Bson query;
}
db.runCommand(DistinctQuery("stuff", "site", Bson.emptyObject));

The latter is the most efficient, because it can construct the full BSON value in one go.