我有一个MongoDB集合,该集合在单个文档中包含6个字段,例如:
{
"_id" : ObjectId("59d0f2382043f72a443e6ec0"),
"TranDate" : "2017-07-25T18:01:12+08:00",
"TranCode" : "ActFLA_A01_01_",
"TranValue" : "812.34",
"Seq" : "71",
"Configuration" : "10"
},
{
"_id" : ObjectId("59d0f2332043f72a443e1397"),
"TranDate" : "2017-07-25T18:01:12+08:00",
"TranCode" : "ActFLA_A01_01_",
"TranValue" : "87.34",
"Seq" : "71",
"Configuration" : "10"
},
{
"_id" : ObjectId("59d0f2332043f72a443e1397"),
"TranDate" : "2017-07-25T18:01:12+08:00",
"TranCode" : "ActFLA_A01_01_",
"TranValue" : "828.34",
"Seq" : "71",
"Configuration" : "10"
},
{
"_id" : ObjectId("59d0f2342043f72a443e16be"),
"TranDate" : "2017-07-25T00:45:02+08:00",
"TranCode" : "ActFLA_A01_01_",
"TranValue" : "0.00",
"Seq" : "2",
"Configuration" : "0"
}
这是我的查询代码:
Pattern regex = Pattern.compile("^2017-07-25");
Pattern regex2 = Pattern.compile("^ActFLA_A");
Pattern regex3 = Pattern.compile("^10");
DBObject clause1 = new BasicDBObject("TranDate", regex);
DBObject clause2 = new BasicDBObject("TranCode", regex2);
DBObject clause3 = new BasicDBObject("Configuration", regex3);
BasicDBList and = new BasicDBList();
and.add(clause1);
and.add(clause2);
and.add(clause3);
DBObject query = new BasicDBObject("$and", and);
我只得到一个文档,但是我期望3个文档包含(字段)TranDate,TranCode,TranSeq和Configuration,但TranValue除外。
最佳答案
该问题意味着您有兴趣退还满足以下所有条件的(三份)文件:TranDate
以2017-07-25
开头TranCode
以ActFLA_A
开头Configuration
以10
开头
以下代码将满足该要求:
@Test
public void aQuery() {
MongoClient mongoClient = new MongoClientFactory().create();
MongoCollection<Document> collection = mongoClient.getDatabase("stackoverflow").getCollection("ors");
Pattern regex = Pattern.compile("^2017-07-25");
Pattern regex2 = Pattern.compile("^ActFLA_A");
Pattern regex3 = Pattern.compile("^10");
Bson clause1 = Filters.regex("TranDate", regex);
Bson clause2 = Filters.regex("TranCode", regex2);
Bson clause3 = Filters.regex("Configuration", regex3);
Bson query = Filters.and(clause1, clause2, clause3);
Assert.assertEquals(3, collection.count(query));
// let's have a look at the matched docs ...
FindIterable<Document> documents = collection.find(query);
for (Document document : documents) {
logger.info(document.toJson());
}
}
给定OP中包含的样本文档,上述测试记录以下内容:
2017-10-01 17:31:59 [main] INFO c.s.mongo.MongoClientTest - { "_id" : { "$oid" : "59d0f2382043f72a443e6ec0" }, "TranDate" : "2017-07-25T18:01:12+08:00", "TranCode" : "ActFLA_A01_01_", "TranValue" : "812.34", "Seq" : "71", "Configuration" : "10" }
2017-10-01 17:31:59 [main] INFO c.s.mongo.MongoClientTest - { "_id" : { "$oid" : "59d0f2332043f72a443e1397" }, "TranDate" : "2017-07-25T18:01:12+08:00", "TranCode" : "ActFLA_A01_01_", "TranValue" : "87.34", "Seq" : "71", "Configuration" : "10" }
2017-10-01 17:31:59 [main] INFO c.s.mongo.MongoClientTest - { "_id" : { "$oid" : "59d11663c26584cd8b7a0ee8" }, "TranDate" : "2017-07-25T18:01:12+08:00", "TranCode" : "ActFLA_A01_01_", "TranValue" : "828.34", "Seq" : "71", "Configuration" : "10" }