我正在使用带有 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 } } ] }
]
} )`
最佳答案
您还可以尝试下面的代码,它为 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);
关于java - 如何在 mongodb 和 Java 中 $and 两个文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31982853/