Push dictionary in list using values of other elements

Hello! I have a collection with records like these

{
    key: [{key1: 2}, {key1: 0}, {key1: 3}]
}

And I need to push a new dictionary in that list. (Push something like {key1: x}) x must be an smallest element from range 0, 1, 2 … infinity which is not in values of other dictionaries. (I hope that it is understandable)

For given example an solution would push {key1: 1} to list.
How to do it? Thanks.

Hi Nikita,

I believe you wanted to printout the smallest value in the key1 of key array. I have inserted sample 3 docs to the test collection and wrote a aggrgation query to get the smallest of key value in that array:

MongoDB Enterprise mflix-shard-0:PRIMARY> db.pushc.find()
{ "_id" : ObjectId("619b4bfe38b4bdc076230a0d"), "key" : [ { "key1" : 2 }, { "key1" : 0 }, { "key1" : 3 } ] }
{ "_id" : ObjectId("619b4cd438b4bdc076230a0e"), "key" : [ { "key1" : 5 }, { "key1" : 9 }, { "key1" : 8 } ] }
{ "_id" : ObjectId("619b4ce138b4bdc076230a0f"), "key" : [ { "key1" : 56 }, { "key1" : 17 }, { "key1" : 80 } ] }
MongoDB Enterprise mflix-shard-0:PRIMARY> db.pushc.aggregate([ { $project :{ minkey:{$min:{$map:{input:"$key",as:"key",in:"$$key.key1"}}}}} ])
{ "_id" : ObjectId("619b4bfe38b4bdc076230a0d"), "minkey" : 0 }
{ "_id" : ObjectId("619b4cd438b4bdc076230a0e"), "minkey" : 5 }
{ "_id" : ObjectId("619b4ce138b4bdc076230a0f"), "minkey" : 17 }
MongoDB Enterprise mflix-shard-0:PRIMARY> 

Please let me know if my understanding is wrong here.

I have mapped the array and used $min to compare the key1 insdie the key array so it could project the minimum value.

Thanks,
Darshan