如何在mongodb和Java中对两个文档进行$and操作?

6

我正在使用Java 3.0驱动程序与mongodb。我有一个场景,在这个场景中我必须执行逻辑和,即$and,在我的查询中。例如,我已经创建了两个文档,我正在尝试做类似于这样的事情:

iterable = mongoDatabase.getCollection("restaurants").find(
                                              new Document("$and", asList(abc,
                                                     updatedDocumentTypeOne)));

其中abc是一份文档,updatedDocumentTypeOne是另一份文档。我在MongoDB手册中发现了这个,但我遇到了错误,需要首先创建asList方法。

或者如何在Java中复制以下内容:

db.inventory.find( {
    $and : [
        { $or : [ { price : 0.99 }, { price : 1.99 } ] },
        { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
    ]
} )`
2个回答

6
您可以尝试以下代码,它在Java中添加了一个查询复制过滤器:
// Where db is the object reference of "inventory" collection's database
 MongoCollection<Document> inventory = db.getCollection("inventory");

//List for result return
 List<Document> result = new ArrayList<Document>();

//Query replication in Java and return result into the list
 inventory.find(Filters.and(
            Filters.or(Filters.eq("price", 0.99),Filters.eq("price", "1.99")),
            Filters.or(Filters.eq("sale", true),Filters.lt("qty", 20))
            )).into(result);

2

将asList()更改为Arrays.asList()

你指定了asList(),而不是Arrays.asList()。所以编译器正在查找方法asList(),但该方法不存在。

请检查以下代码:

iterable = mongoDatabase.getCollection("restaurants").find(
                                                new Document("$and", Arrays.asList(abc,
                                                        updatedDocumentTypeOne)));

针对您上述的查询,您可以按照以下方式编写代码:
/* First OR condition */
Document price1 = new BasicDBObject("price",0.99);
Document price2 = new BasicDBObject("price",1.99);

BasicDBList or_first = new BasicDBList();
or_first.add(price1);
or_first.add(price2);
DBObject query = new BasicDBObject("$or", or_first);

/* Second OR condition */
boolean val = true;
Document sale = new BasicDBObject("sale",val);
Document qty = new BasicDBObject("qty", new BasicDocument("$lt",20));

BasicDBList or_second = new BasicDBList();
or_second.add(sale);
or_second.add(qty);
DBObject query = new BasicDBObject("$or", or_second);

/* AND condition logic */
BasicDBList and_op = new BasicDBList();
and_op.add(or_first);
and_op.add(or_second);

iterable = mongoDatabase.getCollection("restaurants").find( new Document("$and", and_op )); 

它对我不起作用,我正在使用MongoDB Java驱动程序3.0。 - Shaik Mujahid Ali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接