Aymen Kanzari
Aymen Kanzari

Reputation: 2013

mongodb get the list of id

I have the below user collection

{  
   "_id":"562e7c594c12942f08fe4192",
   "shape":"square",
   "color":"blue"
},
{  
   "_id":"562e7c594c12942f08fe4193",
   "shape":"square",
   "color":"black"
}

How can i get only the _id attribute with mongodb to get the list of id

With jpa the query is like below

@Query("SELECT u.id FROM User u)
Set<String> findUserIds();

Upvotes: 0

Views: 50

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

If you are using MongoRepository, you can write it this way:

@Query(value="{}", fields="{_id : 1}")
List<User> findIds();

This will only populate the id field within the user objects, which then can be mapped to a collection of strings.

Upvotes: 1

Related Questions