【问题标题】:Mongodb distinct with in clause in javajava中的mongodb与in子句不同
【发布时间】:2015-12-18 13:11:27
【问题描述】:

我有一个 mongo db 查询,我正在尝试将其转换为 java 驱动程序查询。

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

我的尝试没有成功。任何人都可以帮我将上述查询转换为等效的 java 代码。提前致谢。

【问题讨论】:

  • 如果您尝试了很多次,能否请您在问题中提供那些“很多”次尝试?这样,其他尝试帮助的人将有一个起点,可以更快地解决问题!

标签: java mongodb mongodb-query


【解决方案1】:

这可以通过 distinct iterable 并向其添加过滤器来完成。

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

这里的 sourceReferenceList 是一个包含所需过滤值的数组列表。

【讨论】:

    【解决方案2】:

    您可以获取带有或不带有不同查询的文档。

    1) 没有明确的查询: 只需使用 HashSet 过滤重复项。

    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);
        }
    

    这应该会给你想要的输出。这里重复数据是由应用程序而不是数据库删除的,但易于使用。

    2) 具有不同的查询:

    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();
        }
    

    这将给出不同 sourceName 字段的列表。同样,您必须遍历使用投影获取的文档列表,并如第一种方法所示过滤查询。

    我不是一个优秀的程序员,如果你知道更好的方法,很高兴编辑这段代码。

    参考:Java MongoDB 3.0 driver query distinct without filter

    【讨论】:

    • 你好,harravmb,当我在没有不同查询的情况下使用时,我得到一个编译错误,其中使用 in 的地方类似于 GetSourceName 类型的 in(String, List) 方法未定义。
    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 2011-03-05
    • 2013-02-26
    • 2020-06-15
    • 2010-12-01
    • 1970-01-01
    • 2014-05-12
    相关资源
    最近更新 更多