如何将作为字符串数组存储的mongodb字段值检索到java ArrayList中

时间:2016-02-09 06:57:29

标签: mongodb-query mongodb-java

文档结构是:

db.lookupdata.insert({ parent_key : "category" , key :    "accessories" , value : ["belts","cases","gloves","hair","hats","scarves","sunglasses","ties","wallets","watches"]})

我想在java数组列表中存储数组字段值 我找到这样的文件:

 FindIterable<Document> iterable1 = docCollectionLookup.find(Filters.eq("parent_key", "category"));
        Iterator<Document> iter1=iterable1.iterator();
        while(iter1.hasNext())
        {
            Document theObj = iter1.next();

            categotyLookUpMap.put(theObj.getString("key"), list);

        }

现在我如何在ArrayList

中检索数组字段值(键:“value”)

1 个答案:

答案 0 :(得分:0)

您可以在ArrayList中检索数组字段值(键:&#34;值&#34;),就像检索字符串字段键一样。请参考以下内容:

FindIterable<Document> iterable1 = docCollectionLookup.find(Filters.eq("parent_key", "category"));
Iterator<Document> iter1=iterable1.iterator();

//Create a HashMap variable with type <String,ArrayList>,according to your needs 
Map<String,ArrayList> categotyLookUpMap = new HashMap<String,ArrayList>();

while(iter1.hasNext())
{
   Document theObj = iter1.next();
   //Get method of Document class will return object,parse it to ArrayList
   categotyLookUpMap.put(theObj.getString("key"), (ArrayList)theObj.get("value"));
}

或者,您可以使用Java中的MongoDB对象文档映射器Morphia。您可以从here

设置依赖关系/下载JAR

首先,创建LookupData类以映射到lookupdata集合。注释@Id是必需的,否则将抛出异常消息&#34;没有字段用@Id注释;但它是必需的&#34;。因此,为它创建一个_id字段。

@Entity("lookupdata")
public class LookupData {

@Id
String _id ;

@Property("parent_key")
String parentKey;

String key;

ArrayList<String> value;

public String get_id() {
    return _id;
}
public void set_id(String _id) {
    this._id = _id;
}

public String getParentKey() {
    return parentKey;
}

public void setParentKey(String parentKey) {
    this.parentKey = parentKey;
}

public String getKey() {
    return key;
}

public void setKey(String key) {
    this.key = key;
}

public void setValue(ArrayList<String> value) {
    this.value = value;
}

public ArrayList<String> getValue() {
    return value;
}

}

检索数组字段值如下:

MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost"));

Morphia morphia = new Morphia();
morphia.map(LookupData.class);           

//lookupdata collection is under my local db "tutorials" in this case
Datastore datastore = morphia.createDatastore(mongoClient, "tutorials");
Map<String,ArrayList> categotyLookUpMap = new HashMap<String,ArrayList>();

LookupData lookupData = datastore.find(LookupData.class).get();
categotyLookUpMap.put(lookupData.getKey(), lookupData.getValue());