2

I have a nested JSON document like:

    {
        "docId": 1901603742,
        "sl": [ {"slid","val"}],
        "accounts": {
            "123": {
                "smartAccountId": "123",
                "smartAccountName": "Dummy name",
                "101": {
                    "virtualAccountId": "101",
                    "virtualAccountName": "DEFAULT"
                },
                "102": {
                    "virtualAccountId": "102",
                    "virtualAccountName": "DEFAULT"
                }
            },
            "234": {
                "smartAccountId": "234",
                "smartAccountName": "Dummy name",
                "201": {
                    "virtualAccountId": "201",
                    "virtualAccountName": "DEFAULT"
                }
            }

    }
}

here I need to put an Index on the "smartAccountId" and "virtualAccountId". The problem is the key for the nested document is not fixed, its the "smartAccountId" or "virtualAccountId" we are using as the key (123 in the example), how can we get such a document indexed on MongoDB?

Thanks

PS: I already have an array in the original document, so cant introduce one more array, as we wont be able to index more than one array in a given document.

Prashant Mishra
  • 330
  • 4
  • 15
  • 2
    You've identified the problem already, you can't put an index on dynamic keys. Consider changing the schema to have embedded documents or referenced models (depending on your application design). The embedded schema can be for instance `{ "accounts": [ { "_id": "123", "smartAccountId": "123", "smartAccountName": "Dummy name", ... }, { "_id": "234", "smartAccountId": "234", ... } ] }` and you can create the index as `db.collection.createIndex({"accounts._id" : 1})` – chridam Apr 27 '17 at 07:52
  • @chidram I already have an array in the original document, so cant introduce one more array, as we wont be able to index more than one array in a given document. Any other way to index a document with a dynamic key? Something like ` db.collection.createIndex({accounts.$:1}) ` – Prashant Mishra Apr 27 '17 at 09:29
  • Short answer; no, you can't. – chridam Apr 27 '17 at 09:35
  • @PrashantMishra you want to create index for a field that may or may not exist? is it something like this...? – kapilpatwa93 Apr 27 '17 at 10:15
  • @kapil.dev yes, basically I want to use nested objects instead of arrays, as we cannot have a composite indexes on two arrays (which is a requirement here). So, I was wondering if there's a way to index an object at a certain level, something like `createIndex(accounts.$)` or `createIndex(accounts.$. smartAccountId )` – Prashant Mishra May 07 '17 at 15:22

0 Answers0