1

My MongoDB documents look something like this:

{
  "person_id": 12345,
  "first_name": "John",
  "last_name": "Doe",
  ...
}

I now want a query that gives me a Collection<Long> of person_ids, with some filters applied. Filtering works fine, but MongoCollection.find returns a MongoCollection of Documents. Is there an implicit way to just get the values (12345), not key-value-pairs ("person_id" : 12345)?

Right now I'm just filling a new Collection by iterating over the result, extracting the values one by one. If there's no other way to do it, is there any point in using a projection to restrict the returned fields to person_id, or is that just overhead?

user2727133
  • 149
  • 1
  • 12
  • Doesn't look like this is possible :( https://stackoverflow.com/questions/25589113/how-to-select-a-single-field-for-all-documents-in-a-mongodb-collection – Not a JD Mar 28 '19 at 23:41
  • MongoDB returns BSON Documents from `find()` and it's "alike" methods. There is no exception, with the distinction of the `distinct()` method ( and that still returns BSON Documents internally ). If you want single values only, then you either convert to Array/List or iterate a returned cursor and extract the "values only" in a loop or similar construct. FYI a `BsonDocument` or `BasicDBObject` is basically an abstraction of `Map`. – Neil Lunn Mar 29 '19 at 08:39

0 Answers0