鍍金池/ 問答/Java  數據庫  HTML/ java查詢mongodb,某個查詢條件是一個數組,怎么實現

java查詢mongodb,某個查詢條件是一個數組,怎么實現

{ "_id" : ObjectId("5a5ec3cd50a8xxxxxxdb82"), "date" : "2018-01-17 11:32:29", "type" : "A", "id" : "xxx001"}
{ "_id" : ObjectId("5a5ec3cd50a8xxxxxxdb82"), "date" : "2018-01-17 11:32:29", "type" : "A", "id" : "xxx001"}
{ "_id" : ObjectId("5a5ec3cd50a8xxxxxxdb82"), "date" : "2018-01-17 11:32:29", "type" : "B", "id" : "xxx001"}
{ "_id" : ObjectId("5a5ec3cd50a8xxxxxxdb82"), "date" : "2018-01-17 11:32:29", "type" : "C", "id" : "xxx001"}
{ "_id" : ObjectId("5a5ec3cd50a8xxxxxxdb82"), "date" : "2018-01-17 11:32:29", "type" : "C", "id" : "xxx001"}
{ "_id" : ObjectId("5a5ec3cd50a8xxxxxxdb82"), "date" : "2018-01-17 11:32:29", "type" : "C", "id" : "xxx001"}
{ "_id" : ObjectId("5a5ec3cd50a8xxxxxxdb82"), "date" : "2018-01-17 11:32:29", "type" : "A", "id" : "xxx002"}

根據id和type去查詢,其中type可能多個也可能沒有,只用id查詢:
比如:
id=xxx001的所有記錄-這個好弄
id=xxx001且type=A的所有記錄-這個也好弄

id=xxx001且type=A和B的所有記錄-這個怎么實現
id=xxx001且type=C和B的所有記錄-這個怎么實現

現在用下面的方式,但是type是多個條件就不管用了,只能一個
data.put("id", "xxx001");
data.put("type", "A"); //這里只能填一個,不好多個
basicDBObject = new BasicDBObject(data);
FindIterable<Document> iter = document.find(basicDBObject);

求解各位大神,java實現
謝謝

回答
編輯回答
貓小柒

Google一下都有現成的:MongoDB Java: Finding objects in Mongo using QueryBuilder $in operator returns nothing

public static void getDocuments(List<Integer> documentIds) {
    BasicDBList docIds = new BasicDBList();
    docIds.addAll(documentIds)
    DBObject inClause = new BasicDBObject("$in", docIds);
    DBObject query = new BasicDBObject("Id", inClause);
    DBCursor dbCursor = mongoRule.getDatabase().getCollection("mycollection").find(query);
    System.out.println(dbCursor == null);
    if (dbCursor != null) {
        while (dbCursor.hasNext()) {
            System.out.println("object -  " + dbCursor.next());
        }
    }
}

我注意到你的_id全是一樣的,所以你是不是已經使用$unwind把一個數組展開了?

2017年4月16日 03:23