0

这些是我的 Mongo DB 员工 Collection 中存在的 3 个示例记录。

如果您能观察到,下面显示的记录之一中缺少一个名为“国家”的字段。

db.employees.find().pretty()

{
        "_id" : ObjectId("513331a227a414395af00904"),
        "name" : "Ravi",
        "age" : "21",
        "dept" : "DEV",
        "country" : "IND"
}


{
        "_id" : ObjectId("513331e627a414395af00905"),
        "name" : "Pavan",
        "age" : "23",
        "dept" : "DEV"
}

{
        "_id" : ObjectId("513331e627a414395af00907"),
        "name" : "Saagy",
        "age" : "22",
        "dept" : "DEV",
        "country" : "US"
}

我正在研究现有的 Mongo DB,其中某些键可能不存在于集合中的旧记录中,如上面的记录所示。

现在使用下面的代码,我只得到一条记录作为响应,因为另一条记录中不存在国家键。

    DBCollection mycollection = db.getCollection("employees");
    BasicDBObject query = new BasicDBObject();
    query.put("dept", "DEV");
    query.put("country", "IND");

    DBCursor cursor = mycollection.find(query);

    while (cursor.hasNext()) 
    {
    System.out.println(cursor.next());
    }

我的要求是,如果国家/地区关键字不存在,那么它应该被视为 IND,并且也应该包含在响应中。

这可能吗 ??

请告诉我 。

更新部分

我试过使用 $exists ,但我得到一个异常

public class Test {

    public static void main(String args[]) throws UnknownHostException {
        Mongo mongo = new Mongo();
        DB db = mongo.getDB("test");
        DBCollection mycollection = db.getCollection("employees");

        BasicDBObject query = new BasicDBObject();
        query.put("dept", "DEV");
        query.put("country", "IND");
        DBObject subquery = new BasicDBObject("country", new BasicDBObject("$exists", false));

        DBCursor cursor = mycollection.find(query,subquery);

        while (cursor.hasNext()) 
        {
        System.out.println(cursor.next());
        }




    }



Exception in thread "main" com.mongodb.MongoException: Unsupported projection option: $exists
    at com.mongodb.MongoException.parse(MongoException.java:82)
    at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:314)
    at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:295)
    at com.mongodb.DBCursor._check(DBCursor.java:368)
    at com.mongodb.DBCursor._hasNext(DBCursor.java:459)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:484)
    at com.Test.main(Test.java:26)
4

1 回答 1

1

您可以结合使用 $or 和 $exists 来解决此问题。这应该是正确的:

public class Test {

public static void main(String args[]) throws UnknownHostException {
    Mongo mongo = new Mongo();
    DB db = mongo.getDB("test");
    DBCollection mycollection = db.getCollection("employees");

    DBObject clause1 = new BasicDBObject("country", "IND");  
    DBObject clause2 = new BasicDBObject("$exists", false);    
    BasicDBList or = new BasicDBList();
    or.add(clause1);
    or.add(clause2);

    BasicDBObject query = new BasicDBObject();
    query.put("dept", "DEV");
    query.put("$or", or);

    DBCursor cursor = mycollection.find(query);

    while (cursor.hasNext()) 
    {
    System.out.println(cursor.next());
    }




}
于 2013-03-03T14:54:59.497 回答