使用java monogodb限制查找运算符的字段

时间:2015-09-22 03:49:33

标签: javascript java arrays mongodb mongoose

我有一组用户,其中包含一个包含他朋友ID的嵌入式文档数组。

{
  "_id": "11",
  "name": "jhon",
  "userFriends": [
    {
      "user_id": "22"
    },
    {
      "user_id": "12"
    }
  ]
}

我希望所有朋友ID都在_id =“11”;

我正在尝试使用java代码

BasicDBObject fields = new BasicDBObject().append("userFriends.user_id", 1); 
BasicDBObject query = new BasicDBObject().append("_id", "1"); 
DBCursor results = coll.find(query, fields);

但是我收到了这个错误:

  

MongoCollection类型中的方法find(Bson,Class)不适用于参数(BasicDBObject,BasicDBObject):

1 个答案:

答案 0 :(得分:0)

您正在尝试使用较新版本的MongoDB(3.0+)并以较旧的方式编写代码。对于2.13版本或3.0(使用一些已弃用的方法),这样可以正常工作。

    MongoClient mongoClient = new MongoClient(new ServerAddress(
            "localhost", 27017));
    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = (DB) mongo.getDB("testDB");
    DBCollection collection = db.getCollection("coll");
    BasicDBObject fields = new BasicDBObject().append(
            "userFriends.user_id", 1).append("_id", 0);
    BasicDBObject query = new BasicDBObject().append("_id", "11");
    DBObject dbObj = collection.findOne(query, fields);
    BasicDBList list = (BasicDBList) dbObj.get("userFriends");

    String[] arr = new String[list.size()];

    for (int i = 0; i < list.size(); i++) {

        DBObject obj = (DBObject) list.get(i);
        arr[i] = (String) obj.get("user_id");
    }

在较新的风格中,

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

    MongoClient mongoClient = new MongoClient(new ServerAddress(
            "localhost", 27017));
    MongoDatabase db = mongoClient.getDatabase("testDB");
    MongoCollection<Document> collection = db.getCollection("coll");
    Document doc = collection.find(eq("_id", "11")).projection(Projections.include("userFriends.user_id")).first();

    List list = (List) doc.get("userFriends");
    String[] arr = new String[list.size()];

    for (int i = 0; i < list.size(); i++) {
        Document obj = (Document) list.get(i);
        arr[i] = (String) obj.get("user_id");
    }

有关使用3.0 with Java的更多详细信息,请参阅Quick Tour