0

I have a mongodb query: (Give me the settings where account='test')

db.collection_name.find({"account" : "test1"}, {settings : 1}).pretty();

where I get the following sample output:

{
    "_id" : ObjectId("49830ede4bz08bc0b495f123"),
    "settings" : {
        "clusterData" : {
            "us-south-1" : "cluster1",
            "us-east-1" : "cluster2"
        },
    },

What I'm looking for now, is to give me the account where the clusterData has more than 1 key.

I'm only interested in listing those accounts with (2) or more keys.

I've tried this: (but this doesn't work)

db.collection_name.find({'settings.clusterData.1': {$exists: true}}, {account : 1}).pretty();

Is this possible to do with the current data structure? I don't have the option to redesign this schema.

noober
  • 1,427
  • 3
  • 23
  • 36
  • Have you looked at https://stackoverflow.com/questions/7811163/query-for-documents-where-array-size-is-greater-than-1 ? – jeanr Aug 12 '17 at 15:53

1 Answers1

0

Your clusterData field is not an array which is why you cannot just filter the number of elements it has. There is a way, though, to get what you want via the aggregation framework. Try this:

db.collection_name.aggregate({
    $match: {
        "account" : "test1"
    }
}, {
    $project: {
        "settingsAsArraySize": { $size: { $objectToArray: "$settings.clusterData" } },
        "settings.clusterData": 1
    }
}, {
    $match: {
        "settingsAsArraySize": { $gt: 1 } 
    }
}, {
    $project: {
        "_id": 0,
        "settings.clusterData": 1
    }
}).pretty();
dnickless
  • 10,733
  • 1
  • 19
  • 34