我在mongodb数据库中有一个字段推文,其中包含存储的推文的几个特征。用户字段之一,其中包含有关发布推文的用户的信息。我想检索给定用户的id,存储在数据库中的用户的一些其他信息。数据库的结构:
_id
tweet_info
user
id
description
default_profile
我想要,拥有用户ID来检索字段描述和default_profile。我应该在这里执行什么查询?我的代码到现在为止:
MongoClient mongoClient = new MongoClient("..", 27017);
DB db = mongoClient.getDB("...");
DBCollection coll = db.getCollection("...");
BasicDBObject query = new BasicDBObject("??, ??);
DBCursor cursor = coll.find(query);
System.out.println(cursor);
try {
while (cursor.hasNext()) {
final DBObject result = cursor.next();
Map<String, Object> value = (Map<String, Object>) result.get("user");
System.out.println(value.get("default_profile"));
System.out.println(value.get("description"));
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
如何在给定user.id的情况下检索此字段?我正在尝试的是以下内容:
BasicDBObject query = new BasicDBObject("user.id", 975789703); // id example
DBCursor cursor = coll.find(query);
System.out.println(cursor);
try {
while (cursor.hasNext()) {
final DBObject result = cursor.next();
Map<String, Object> value = (Map<String, Object>) result.get("user");
System.out.println(value.get("default_profile"));
System.out.println(value.get("default_profile_image"));
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
当我尝试执行以下查询时:
BasicDBObject query = new BasicDBObject("user.name", "");
它返回所有用户。几分钟后,我收到消息:
Cursor id=0, ns=iti_se.cms, query={ "user.id" : 507813128}, numIterated=0, limit=20,
readPreference=primary
Exception in thread "main" com.mongodb.MongoException: interrupted at shutdown
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 twitter4j.examples.tweets.UpdateStatus.default_image(UpdateStatus.java:94)
at twitter4j.examples.tweets.UpdateStatus.main(UpdateStatus.java:112)
Java结果:1
答案 0 :(得分:2)
试试这个:
BasicDBObject query = new BasicDBObject("user.id", userId);