从mongodb对象返回属性-Java驱动程序
我有像mongo一样的东西从mongodb对象返回属性-Java驱动程序,java,mongodb,Java,Mongodb,我有像mongo一样的东西 { "name" : "mongo", "values" : [ { "date" : "02-23-2015", "price" : "5" }, { "date" : "02-23-15", "price
{
"name" : "mongo",
"values" : [
{
"date" : "02-23-2015",
"price" : "5"
},
{
"date" : "02-23-15",
"price" : "6"
},
{
"date" : "02-22-15",
"price" : "7"
}
]
}
我正在使用Java驱动程序,我能够通过如下查询提取此对象:
QueryBuilder builder = new QueryBuilder();
DBObject nameQuery = new BasicDBObject("name", "mongo");
builder.and(nameQuery);
DBObject fullQuery = builder.get();
然而,我想要的是提取所有的价格值,并将其存储在一个数组中-现在我只能返回整个对象..在文档中对这样的子集进行迭代没有很好的解释,举个例子会很有帮助
任何帮助都将不胜感激
编辑:好的,现在我可以遍历该数组中的对象,但它没有利用mongo内置功能,速度自然会变慢:
while (curs.hasNext())
{
DBObject o = curs.next();
BasicDBList values = (BasicDBList) o.get("values");
BasicDBObject[] valuesArray = values.toArray(new BasicDBObject[0]);
for(BasicDBObject dbObj : valuesArray) {
name = dbObj.getString("name");
}
}
这允许我提取我想要的任何东西,但我知道有一种更有效的方法。任何帮助都将是巨大的,谢谢我认为它应该可以工作,或者它可以让您接近解决方案:
DB db = this.getConnection();
DBCollection coll = db.getCollection(collection);
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mongo");
cursor = coll.find(searchQuery);
DBObject resultElement = null;
List <String> prices = new ArrayList<String>();
while(cursor.hasNext()){
resultElement = cursor.next();
prices.add ((String) resultElement.get("values.price"));
}
DB=this.getConnection();
DBCollection coll=db.getCollection(collection);
BasicDBObject searchQuery=新建BasicDBObject();
searchQuery.put(“name”、“mongo”);
cursor=coll.find(搜索查询);
DBObject resultElement=null;
标价=新的ArrayList();
while(cursor.hasNext()){
resultElement=cursor.next();
prices.add((字符串)resultElement.get(“values.price”);
}
希望有帮助。DBCollection.find()方法使用第二个参数keys,该参数允许您定义结果中应包含哪些字段。像这样使用它:
collection.find(query, new DBObject("values.price":1);
{
"values" : [
{
"price" : "5"
},
{
"price" : "6"
},
{
"price" : "7"
}
]
}
这将返回一个带有值数组的文档,该数组仅包含以下价格:
collection.find(query, new DBObject("values.price":1);
{
"values" : [
{
"price" : "5"
},
{
"price" : "6"
},
{
"price" : "7"
}
]
}
好的,但是我如何提取这些值呢?我可以通过强制转换到
BasicDBList
然后调用toArray
方法来获得这个数组,方法是对这个BasicDBList
对象进行调用…然后我只需迭代对象数组。有没有一种内置的方法可以做到这一点?看我的更新上面你的方式只是关于我会怎么做。我不太清楚你所说的更内置的方式是什么意思,以及这种方式是如何变慢的