Mongodb | Check if any other key exist in object field other than given key in object field | length of object field type

Viewed 82

We have one use case. Let's suppose I have two documents as given below.

{
  "_id": ObjectID('123'),
  "test": {
     "a":1,
      "b":1
   }
},
{
  "_id": ObjectID('456'),
  "test": {
     "a":1
   }

Now I want those result whose "test" field has property other than "a" or in another way, I want those objects which have multiple keys/properties in a "test" field or to check the size of an object greater than 1

So, the result will be:

{
   "_id": ObjectID('123'),
   "test": {
      "a":1,
       "b":1
    }
}

I tried to make a query for the above output as shown below and it working as expected

db.col.find({"test": {"$gt": {"a": 1} }})

So, is that the right thing to do? Any downside of doing it? We want to lever-age indexes as well

Please let me know your inputs on this.

Thanks.

1 Answers
Related