Joseph Blair
Joseph Blair

Reputation: 1455

Is it possible to use the Mongo $natural operator in Spring Data?

I was looking to use the $natural operator in Spring Data MongoDB, as documented here:

https://docs.mongodb.org/v3.0/reference/operator/meta/natural/

Is this possible to do using the MongoTemplate class? Thanks.

Upvotes: 2

Views: 1235

Answers (1)

mp911de
mp911de

Reputation: 18119

It is possible to use $natural in at least three styles where 1. and 2. are probably what you're looking for:

1. Using Sort with Query

Query query = new Query().with(new Sort(Direction.ASC, "$natural"));

use the query afterwards with MongoTemplate. The query carries a sort document like:

{ "$natural" : 1}

2. Using BasicQuery

BasicQuery allows using own DBObjects for the query document, the fields ("projection") and sorting.

BasicQuery basicQuery = new BasicQuery(new BasicDBObject());
basicQuery.setSortObject(new BasicDBObject("$natural", 1));

3. Using execute and CollectionCallback

This is the most extensive way in which you're getting access to the DBCollection and you can use the native MongoDB driver API. See Spring Data Mongo docs for more details.

Upvotes: 2

Related Questions