sql >> Base de Datos >  >> NoSQL >> MongoDB

MongoDB Java - ¿Empujar a una matriz anidada?

Puede hacer referencia a la matriz en el subdocumento "nivel1" utilizando la notación de puntos. Entonces, en lugar de crear DBObjects anidados como lo ha hecho, simplemente necesita:

coll.update(entry, new BasicDBObject("$push", new BasicDBObject("level1.arr1", "val2")));

Escribí una prueba para mostrar que esto funciona:

@Test
public void shouldPushANewValueOntoANesstedArray() throws UnknownHostException {
    final MongoClient mongoClient = new MongoClient();
    final DBCollection coll = mongoClient.getDB("TheDatabase").getCollection("TheCollection");
    coll.drop();

    //Inserting the array into the database
    final BasicDBList array = new BasicDBList();
    array.add("val1");

    final BasicDBObject entry = new BasicDBObject("level1", new BasicDBObject("arr1", array));
    coll.insert(entry);

    // results in:
    // { "_id" : ObjectId("51a4cfdd3004a84dde78d79c"), "level1" : { "arr1" : [ "val1" ] } }

    //do the update
    coll.update(entry, new BasicDBObject("$push", new BasicDBObject("level1.arr1", "val2")));
    // results in:
    // { "_id" : ObjectId("51a4cfdd3004a84dde78d79c"), "level1" : { "arr1" : [ "val1", "val2" ] } }
}