ryan embgrets
ryan embgrets

Reputation: 23

How could I make sure that my mongo query uses indexes

I am using mongo-driver mongo's official driver for Go. I have below index on the collection,

// 1
[
    {
        "v": NumberInt("2"),
        "key": {
            "_id": NumberInt("1")
        },
        "name": "_id_",
        "ns": "cgrates.cdrs"
    },
    {
        "v": NumberInt("2"),
        "key": {
            "setuptime": NumberInt("-1"),
            "account": NumberInt("1"),
            "runid": NumberInt("1")
        },
        "name": "setuptime_NumberInt(\"-1\")_account_NumberInt(\"1\")_runid_NumberInt(\"1\")",
        "ns": "cgrates.cdrs"
    }
]

And below is how my filter in golang code looks like.

filter := bson.M{"setuptime": bson.M{"$gt": startTime, "$lt": endTime}, "account": account, "runid": "*default", "originid": callId}

Since, i have composite index, so i wanted golang driver to send the query exactly in the same order i have put above.

But, since filter is a map, so golang does not give guarantee of it being intact. Eventually, i see my golang driver sending queries in out of order.

B....................K....update.....cdrs..lsid......id............A\.2.2......$db.....cgrates.......updates......q......account.....5ee919c63181373a24762676..runid.....*default..originid.%...161060e7-2a37-1239-7684-560001951c52..setuptime......$gt..)..r....$lt.....r......u......$set.#....extrafields.Paid.....0.00125....

Please check above query being sent to mongo, you might notice setuptime being at the last. While in filter it was the on first position.

How could I keep the query order intact or how to query based upon indexes? Does the mongodb handle this automatically?

Upvotes: 0

Views: 404

Answers (2)

Arief Darmawan
Arief Darmawan

Reputation: 47

use bson.D, it will guarantee order

https://www.mongodb.com/docs/drivers/go/current/fundamentals/bson/

Upvotes: 0

D. SM
D. SM

Reputation: 14480

You can verify that indexes are used by using the explain mongo shell method.

You can also provide the fields in different order in mongo shell and verify that the indexes are used.

Upvotes: 1

Related Questions