使用Java中的$ elemMatch实现Mongodb查询

时间:2017-05-19 17:18:07

标签: java mongodb mongodb-query mongo-java-driver

我正在使用Mongo java驱动程序从mongo集合中检索数据。我有以下查询,我试图在java中实现: Json是:

{
    "_id" : ObjectId("56cd284767c74d3d4dd3ec80"),
    "comments" : "Hello",
    "statusLog" : [ 
        {
            "status" : "Submitted",
            "startDate" : ISODate("2015-01-14T05:00:00.000Z"),
            "endDate" : ISODate("2016-02-29T21:24:24.740Z")
        }, 
        {
            "status" : "Active",
            "startDate" : ISODate("2016-02-29T21:24:24.740Z")
        }
    ],
    "createdDate" : ISODate("2015-01-14T05:00:00.000Z")
}

Mongo查询:

db.CollectionName.find({},{_id: 0, createdDate:1, "statusLog": {$elemMatch: {"status":"Submitted"}}});

以下是我编写的java中的查询(mongo java driver 3.4.2):

BasicDBObject query = new BasicDBObject(new BasicDBObject("statusLog",
                new BasicDBObject("$elemMatch", new BasicDBObject("status", "Submitted"))));

运行java代码会返回所有状态日志,而不是我要查找的日志。

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:3)

您应该使用较新的Document/MongoCollection api并使用辅助方法来准备投影。

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Projections.*;

MongoClient mongoClient = new MongoClient(); 
MongoDatabase database = mongoClient.getDatabase("db"); // Get DB

MongoCollection<Document> collection = database.getCollection("collection"); // Get Collection
Bson projection = Projections.fields( excludeId(), include("createdDate"), elemMatch("statusLog", eq("status", "Submitted"))); // Add Projections
FindIterable<Document> iterable = collection.find().projection(projection);

使用旧BasicDBObject/DBCollection api

MongoClient mongoClient = new MongoClient();
DB database = mongoClient.getDB("db");

DBCollection collection = database.getCollection("collection");
BasicDBObject projection = new BasicDBObject(new BasicDBObject("statusLog",new BasicDBObject("$elemMatch", new BasicDBObject("status", "Submitted"))));
collection.find(new BasicDBObject(), projection);

答案 1 :(得分:1)

接受的答案是错误的。 <h2> <?php echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); ?> </h2> 应该在find方法中而不是在投影bson中。例如:

elemMatch