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

To get a value array (instead of a JSON array) for documents with values greater than 50 in MongoDB, use the distinct() method combined with $gt operator and $in for filtering.

Syntax

// Get distinct values greater than threshold
listOfValues = db.collection.distinct("fieldName", {fieldName: {$gt: value}});

// Use $in to find documents with those values
db.collection.find({fieldName: {$in: listOfValues}});

Sample Data

db.demo50.insertMany([
    {"Value": 40},
    {"Value": 100},
    {"Value": 20},
    {"Value": 510}
]);
{
  "acknowledged": true,
  "insertedIds": [
    ObjectId("..."),
    ObjectId("..."),
    ObjectId("..."),
    ObjectId("...")
  ]
}

Display all documents from the collection ?

db.demo50.find();
{ "_id": ObjectId("5e270c02cfb11e5c34d89903"), "Value": 40 }
{ "_id": ObjectId("5e270c05cfb11e5c34d89904"), "Value": 100 }
{ "_id": ObjectId("5e270c07cfb11e5c34d89905"), "Value": 20 }
{ "_id": ObjectId("5e270c11cfb11e5c34d89906"), "Value": 510 }

Method 1: Using distinct() with $in

Get document IDs where Value is greater than 50, then use $in to retrieve full documents ?

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

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

Method 2: Direct Query (Simpler Approach)

For this use case, a direct query is more efficient ?

db.demo50.find({Value: {$gt: 50}});
{ "_id": ObjectId("5e270c05cfb11e5c34d89904"), "Value": 100 }
{ "_id": ObjectId("5e270c11cfb11e5c34d89906"), "Value": 510 }

Key Points

  • distinct() returns an array of unique values, not JSON documents
  • $in operator matches any value in the provided array
  • Direct queries with $gt are simpler for basic filtering

Conclusion

Use distinct() with $in when you need to process the value array before querying. For direct filtering, use $gt operator directly in the find query for better performance.

Updated on: 2026-03-15T02:49:42+05:30

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements