使用java将数据插入mongoDB

时间:2016-06-08 09:28:55

标签: java mongodb

我是MongoDB和NoSQL数据库的新手,并且在使用MongoDB驱动程序时遇到一些问题。 我没有正确理解如何从文档中获取子数组/列表并将数据重新插入其中。 这是我的JSON / BSON对象,我可以轻松保存在MongoDB中。

{
"_id": {
"$oid": "5757df25612c2445af329111"
},
"shop": {
"category": [
  {
    "MobilePhones": [

    ]
  },
  {
    "TV-sets": [

    ]
  },
  {
    "Motherboards": [

    ]
  }
]
}
}

现在我需要从我的商店获取一个类别数组,从我在java POJO类中编写的数组/列表中获取MobilePhones / TV-sets / Motherboards类别的对象。

public class Category extends BasicDBObject implements Serializable {

private List<Goods> goodsList;

private BasicDBObject basicDBObject;

public BasicDBObject getBasicDBObject() {
    return basicDBObject;
}

public void setBasicDBObject(BasicDBObject basicDBObject) {
    this.basicDBObject = basicDBObject;
}

private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public List<Goods> getGoodsList() {
    return goodsList;
}

public void setGoodsList(List<Goods> goodsList) {
    this.goodsList = goodsList;
}

public Category(String name){
    this.name = name;
}

public Category(){}
}

在我写入

时将商品插入此类别
public class Goods extends BasicDBObject implements Serializable {

private String title;

private int price;

private String status;

private BasicDBObject basicDBObject;

public BasicDBObject getBasicDBObject() {
    return basicDBObject;
}

public void setBasicDBObject(BasicDBObject basicDBObject) {
    this.basicDBObject = basicDBObject;
}

public Goods(String title, int price, String status) {
    this.title = title;
    this.price = price;
    this.status = status;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public int getPrice() {
    return price;
}

public void setPrice(int price) {
    this.price = price;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}
}

通过这种方式,我在数据库中获取/创建集合

 DBCollection collection = db.getCollection("shop");
 BasicDBObject dbObject = new BasicDBObject();
 dbObject.put("shop", shop.createCategoriesWithGoods());
 collection.insert(dbObject);

但这种方式并没有帮助我将类别视为

 DBCollection collection = db.getCollection("MobilePhones");

1 个答案:

答案 0 :(得分:0)

这是因为集合是一个表(用SQL术语表示),因此db.getCollection("MobilePhones");正在寻找一个&#34;表&#34;叫MobilePhones。

您已将数据保存到名为&#34; Shop&#34;的集合中。您需要调用getCollection("Shop"),然后您可以对数据执行所需的任何操作。