1

I have some data that looks like this:

{
"_id" : ObjectId("58efcbb9ac808c5c0771b1b0"),
"guid" : "cda474b9-1362-4ffe-99df-5c0783fff8be",
"g" : "SomeString",
"m" : "Something else",
"r" : null,
"dh" : ISODate("2017-04-13T19:00:00.000Z"),
"ei" : 60000,
"v" : [ 
    {}, 
    {}, 
    {}, 
    {}, 
    {
        "last" : 0.0,
        "sum" : 0.0,
        "cnt" : 1,
        "minimum" : 0.0,
        "maximum" : 0.0
    }, 
    {}, 
    {}
]

}

There are numerous documents like this. For a single guid there may be 100 documents like the one above. What I'd like to do is count the number of documents where guid = SOMEGUID and the element "cnt" exists at a specific array element.

The catch is, the array element index is stored in a variable. It's being derived from somewhere else.

This line:

print(myguid + ": " + db.MyCollection.find({"guid" : myguid, "v.4.cnt" : { $exists : true}} ).count());

The above works great. It outputs something like this:

2e605c07-54b2-49e6-8a9f-f31d3dffe57c: 28

My problem is that I don't want to use "4", I have the index stored in a variable called arrayIndex and I'd like to embed that in the query.

A query like this doesn't work:

print(myguid + ": " + db.MyCollection.find({"guid" : myguid, "v.arrayIndex.cnt" : { $exists : true}} ).count());

Any help is appreciated.

BillK
  • 53
  • 4

1 Answers1

2

You can embed index in js code You need something like this.

function count(myguid, index) {
    const query = {"guid": myguid};
    query["v." + index + ".cnt"] = {$exists: true};

    return db.MuCollection.count(query);
}

This method will generate query for specific index and count objects

Usage

count("some-guid", 3);
Gor
  • 2,808
  • 6
  • 25
  • 46
  • That is exactly what I needed. Thanks! – BillK Apr 13 '17 at 22:16
  • Or just `db.MyCollection.find({ guid: myguid, \`v.${arrayIndex}.cnt\`: { $exists : true} }).count()` – Guig Apr 13 '17 at 22:20
  • @Guig. I think this will not work on older versions of mongodb – Gor Apr 13 '17 at 22:22
  • Ah yeah you're right.. `db.MyCollection.find({ guid: myguid, ['v.' + arrayIndex + '.cnt']: { $exists : true} }).count()` would work right? – Guig Apr 13 '17 at 22:26
  • Sure. I think it is es6 support problem. `${}` is es6 operator. so older versions of mongodb would not support it – Gor Apr 13 '17 at 22:57