0

我有一个简单的问题,将实体的嵌入式集合存储和检索到 mongo。我已经检查了这些问题:

如何序列化类?Mongodb保存对象列表

我的理解是保存一个列表对象,该对象的类必须扩展ReflactionDBObject。这适用于保存对象,通过使用嵌入式集合检索它不起作用。

这里有一个简单的测试表明检索嵌入式实体不起作用!

@Test
  public void whatWasStoredAsEmbeddedCollectionIsRetrieved2() {

       BasicDBObject country = new BasicDBObject();

country.put("name", "Bulgaria");

List<City> cities = Lists.newArrayList(new City("Tarnovo"));

country.put("listOfCities", cities);

DBCollection collection = db().get().getCollection("test_Collection");

collection.save(country);

DBCursor object = collection.find(new BasicDBObject().append("name", "Bulgaria"));

DBObject returnedCity = object.next();

DBObject embeddedCities = (DBObject) returnedCity.get("listOfCities");

System.out.println(embeddedCities);
  }

这里是城市班

class City extends ReflectionDBObject {

    String name;


    City() {
    }

    City(String name) {
      this.name = name;
    }

    public String getName() {
      return name;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (!(o instanceof City)) return false;

      City city = (City) o;

      if (name != null ? !name.equals(city.name) : city.name != null) return false;

      return true;
    }

    @Override
    public int hashCode() {
      return name != null ? name.hashCode() : 0;
    }

    @Override
    public String toString() {
      return "City{" +
              "name='" + name + '\'' +
              '}';
    }

  }

System.out.println 语句的输出is [ { "_id" : null }]

现在如何取回嵌入的对象和其中的嵌入列表?

4

1 回答 1

1

如果您不需要定义自己的类 City,您可以使用 BasicDBObjects 定义子文档。我只在 citySubDoc1 和 citySubDoc2 中添加了“名称”字段,但是当然,您可以在这些子文档中添加更多字段。

    // Define subdocuments

    BasicDBObject citySubDoc1 = new BasicDBObject();
    citySubDoc1.put("name", "Tarnovo");    

    BasicDBObject citySubDoc2 = new BasicDBObject();
    citySubDoc2.put("name", "Sofia");

    // add to list

    List<DBObject> cities = new ArrayList <DBObject>();
    cities.add(citySubDoc1);
    cities.add(citySubDoc2);

    country.put("listOfCities", cities);

    collection.save(country);

    // Specify query condition 

    BasicDBObject criteriaQuery = new BasicDBObject();
    criteriaQuery.put("name", "Bulgaria");

   // Perform the read

    DBCursor cursor = collection.find(criteriaQuery);

    // Loop through the results
    try {
        while (cursor.hasNext()) {
           List myReturnedListOfCities = (List) cursor.next().get("listOfCities");
           System.out.println(myReturnedListOfCities);
       }
    } finally {
        cursor.close();
    } 
于 2012-12-03T18:58:37.877 回答