MongoDB内嵌文档过滤(Java方式)

2018-01-13 11:14:09来源:oschina作者:ps_cat人点击

分享

上次写博客关于内嵌文档的过滤,采用的javascript的方式,今天换一种使用Java请求MongoDB, 对内嵌文档进行过滤。


一、javascript方式如下:


db.sales.aggregate([


{


$project: {


items: {


$filter: {


input: "$items",


as: "item",


cond: { $gte: [ "$$item.price", 10 ] }


}


}


}


}


])


二、Java查询如下:


1.导入jar包



org.mongodb
mongodb-driver
${mongodb-driver.version}

2.获取集合:


MongoClientOptions.Builder options = new MongoClientOptions.Builder();
options.connectionsPerHost(300);
options.connectTimeout(15000);
options.maxWaitTime(5000);
options.socketTimeout(0);
options.threadsAllowedToBlockForConnectionMultiplier(5000);
options.build();
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("dbName");
MongoCollection collection = database.getCollection("order");

3.定义块,运用到每个文档


Block printBlock = new Block() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
};

4.写查询语句


List pipeline = Lists.newArrayList();
BasicDBObject filterPipeline = new BasicDBObject("$project",
new BasicDBObject("items",
new BasicDBObject("$filter",
new BasicDBObject("input", "items").append("as", "item").append("cond",
new BasicDBObject("$gte", Arrays.asList("$$item.price", 10)))
)
)
);
pipeline.add(filterPipeline);
collection.aggregate(pipeline).forEach(printBlock);

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台