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.

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

That is exactly what I needed. Thanks!
Or just db.MyCollection.find({ guid: myguid, `v.${arrayIndex}.cnt`: { $exists : true} }).count()
@Guig. I think this will not work on older versions of mongodb
Ah yeah you're right.. db.MyCollection.find({ guid: myguid, ['v.' + arrayIndex + '.cnt']: { $exists : true} }).count() would work right?
Sure. I think it is es6 support problem. ${} is es6 operator. so older versions of mongodb would not support it

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.