0

i have already created a project in spring boot and i can retrieve data from my mongodb database using mongo repository.

i want to write a query in my spring boot app that allows me to get distinct values of an attribute for a given value of another attribute.

Example

 tag1 | tag2  |  tag3
 mod  | test  |  v1
 mod1 | test1 |  v2
 mod1 | test1 |  v3
 mod1 | test1 |  v4

expected: when i call method findbyTag1 ( String tag1) using value mod1 for tag1 variable i want to get distinct values of tag2. In this case the result would be test1.

is there any solution?

1 Answer 1

1

MongoDB Query:-

db.tags.distinct("tag2",{"tag1" : "mod1"});

Equivalent Java Code:-

Please change the database and collection name accordingly.

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class GetDistinctTagsValues {
    public static void main(String[] args) {

        MongoClient client = new MongoClient();

        MongoDatabase database = client.getDatabase("test");

        MongoCollection<Document> collection = database.getCollection("tags");

        DistinctIterable<String> collectionData = collection.distinct("tag2", Filters.eq("tag1", "mod1"), String.class);

        for (String doc : collectionData) {
            System.out.println(doc);
        }

        client.close();

    }

}

Dependency:-

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.4.2</version>
    </dependency>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.