Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return only specific fields for a query in Spring Data MongoDB?

How can we select specific fields in Spring Data Mongo. I tried the following but I got cast exception from Foo to String.

Using @Query

@Query(value="{path : ?0}", fields="{path : 0}")
String findPathByPath(String path);

Non @Query

String findPathByPath(String path);

Here is the document model

@Document(collection = "foo")
public class Foo  {

  String name, path;
  …
}
like image 785
richersoon Avatar asked Aug 20 '15 03:08

richersoon


People also ask

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What is MongoRepository?

MongoRepository is an interface provided by Spring Data in the package org. springframework. data. mongodb.

What is field in MongoDB?

A field required in every MongoDB document. The _id field must have a unique value. You can think of the _id field as the document's primary key. If you create a new document without an _id field, MongoDB automatically creates the field and assigns a unique BSON ObjectId. accumulator.


2 Answers

MongoDB only returns JSON documents for standard queries. What you'd like to see can be achieved by still returning a List<Foo>. The fields property in @Query will cause only the fields set to 1 being returned.

@Query(value="{ path : ?0}", fields="{ path : 0 }")
List<Foo> findByPath(String path);

We usually recommend introducing a dedicted DTO for that so that you prevent the partially filled Foo instance from being handed to save(…) in turn.

Another option is using the aggreation framework but that's more involved.

like image 113
Oliver Drotbohm Avatar answered Oct 06 '22 02:10

Oliver Drotbohm


You can use

Query query = new Query();

query.fields().include("path");
like image 39
Pankaj Mandale Avatar answered Oct 06 '22 03:10

Pankaj Mandale