How do I get a value array (instead a json array) greater than 50 in MongoDB?


To avoid getting json array and get a value array, use $in. For greater than, use MongoDB $gt. Let us create a collection with documents −

> db.demo50.save({"Value":40});
WriteResult({ "nInserted" : 1 })
> db.demo50.save({"Value":100});
WriteResult({ "nInserted" : 1 })
> db.demo50.save({"Value":20});
WriteResult({ "nInserted" : 1 })
> db.demo50.save({"Value":510});
WriteResult({ "nInserted" : 1 })

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

> db.demo50.find();

This will produce the following output −

{ "_id" : ObjectId("5e270c02cfb11e5c34d89903"), "Value" : 40 }
{ "_id" : ObjectId("5e270c05cfb11e5c34d89904"), "Value" : 100 }
{ "_id" : ObjectId("5e270c07cfb11e5c34d89905"), "Value" : 20 }
{ "_id" : ObjectId("5e270c11cfb11e5c34d89906"), "Value" : 510 }

Following is the query to get a value array in MongoDB greater than 50 −

> listOfValues = db.demo50.distinct("_id", {Value:{$gt:50}});
[
   ObjectId("5e270c05cfb11e5c34d89904"),
   ObjectId("5e270c11cfb11e5c34d89906")
]
> db.demo50.find({_id:{$in:listOfValues}});

This will produce the following output −

{ "_id" : ObjectId("5e270c05cfb11e5c34d89904"), "Value" : 100 }
{ "_id" : ObjectId("5e270c11cfb11e5c34d89906"), "Value" : 510 }

Updated on: 03-Apr-2020

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements