3个条件有和不起作用

时间:2014-11-21 21:18:57

标签: mongodb mongodb-query

我是mongodb的新手:

我有一个db包含一些文件如下:

/* 2 */
{
    "_id" : ObjectId("546ea531d38ed4b9eaaa46eb"),
    "name" : "hamed",
"time" : "20141105220011",
    "entity" : [ 
        "10", 
        "11"
    ]
}

/* 3 */
{
    "_id" : ObjectId("546ecb07badc664b0b18ba95"),
    "name" : "ali",
    "time" : "20141105230011",
    "entity" : [ 
        "12", 
        "13"
    ]
}

现在我正在尝试返回包含(11或12之间的实体)和“20141105230011”的所有文档

为此我使用以下代码:

MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("test");
    DBCollection coll = db.getCollection("test");
    BasicDBObject oredrFields = new BasicDBObject();
    DBObject inOp = new BasicDBObject();
    BasicDBObject filtercol = new BasicDBObject();
    inOp.put("$in", new String[] { "10", "1" });
    filtercol.put("_id", 0);
    filtercol.put("name", 1);
    filtercol.put("entity", 1);
    filtercol.put("time", 1);
    oredrFields.put("entity", inOp);
    BasicDBObject andQuery = new BasicDBObject();
    BasicDBObject timeQuery = new BasicDBObject();
    timeQuery.put("time", new BasicDBObject("$gt","20131105241311"));
    List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
    obj.add(timeQuery);
    obj.add(oredrFields);
    obj.add(filtercol);
    andQuery.put("$and", obj);
    DBCursor cursor = coll.find(andQuery);
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

但是当我运行它时,虽然我在数据库中有一些符合条件的数据,但没有任何回报! 有人可以帮忙吗? (我完全糊涂了)

1 个答案:

答案 0 :(得分:2)

您使用不必要的DBObjects复杂了查询。以下代码表示如何使用条件构建DBObject,以使文档与entity in 11 or 12time = 20141105230011匹配。

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("test");
    DBCollection coll = db.getCollection("test");

    DBObject inOp = new BasicDBObject();
    inOp.put("$in", new String[] { "11", "12" });

    BasicDBObject query = new BasicDBObject();
    query.put("entity", inOp);
    query.put("time", "20141105230011");

    BasicDBObject filter = new BasicDBObject().append("_id", 0).
    append("entity", 1).append("time", 1).append("name",1);

    DBCursor cursor = coll.find(query,filter);
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }