简体   繁体   中英

Mongodb distinct with in clause in java

i have a mongo db query which i am trying to convert to java driver query.

 db.sourceReference.distinct('sourceName',{sourceReferenceId:{$in:['565555ef4ee29e068f61dd74','565555ef4ee29e068f61dd73','565555ef4ee29e06882e6151']}})

i was unsuccessful in my attempts. Can any one help me to convert the above query into equivalent java code. Thanks in advance.

This can be done with distinct iterable and adding a filter to it.

DistinctIterable<String> c = mongoDatabase.getCollection("sourceReference").distinct("sourceName",String.class).filter(new Document("sourceReferenceId",new Document("$in",sourceReferenceList)));

Here sourceReferenceList is an array list with required filter values.

You can fetch the documents with and without distinct query.

1) without distinct query: Simply use HashSet to filter the duplicates.

List<String> list = new ArrayList<String>();
list.add('565555ef4ee29e068f61dd74');
list.add('565555ef4ee29e068f61dd73');
list.add('565555ef4ee29e06882e6151');
Bson filter = and(in("sourceReferenceId", list));
Bson projection = fields(include("sourceName"), excludeId());
Set<Document> all = mongoCollection.find(filter)
            .projection(projection).into(new HashSet<Document>());

    for (Document cur : all) {
        System.out.println(cur);
    }

This should give you the desired output. Here duplicate data is removed by application not database but easy to use.

2) with distinct query:

MongoCursor<String> l1 = mongoCollection.distinct("sourceName",
            String.class).iterator();
List<String> l3 = new ArrayList<String>();

    try{
        while(l1.hasNext()){
            l3.add(l1.next());
        }
    }finally{
        l1.close();
    }

This will give the list of distinct sourceName fields. Again you have to loop through the document list fetched using projection, and filter query as shown in the first method.

I'm not a great programmer, if you know better way of doing this, happy to edit this code.

Reference: Java MongoDB 3.0 driver query distinct without filter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM