Find when the keys are unknown in MongoDB?


To find when the keys are unknown, use $addField and $objectToArray. Let us first create a collection with documents −

> db.demo375.insertOne(
...    {
...       "details":{
...          "Name":"John",
...          "Age":23
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a0ae42ae06a1609a00b06")
}
> db.demo375.insertOne(
...    {
...       "details":{
...          "Name":"David",
...          "Age":21
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a0ae42ae06a1609a00b07")
}
> db.demo375.insertOne(
...    {
...       "details":{
...          "Name":"David",
...          "Age":22
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a0ae42ae06a1609a00b08")
}

Display all documents from a collection with the help of find() method −

> db.demo375.find();

This will produce the following output −

{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b06"), "details" : { "Name" : "John", "Age" : 23 } }
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } }
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }

Following is the query to find when the keys are unknown −

> db.demo375.aggregate([
...    { "$addFields": {
...       "UnknownKeys": { "$objectToArray": "$$ROOT" }
...    }},
...    { "$match": { "UnknownKeys.v.Name": "David" }},
...    { "$project": { "UnknownKeys": 0 }}
... ])

This will produce the following output −

{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } }
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }

Updated on: 02-Apr-2020

450 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements