sql >> Database teknologi >  >> NoSQL >> MongoDB

MongoDB Java - Skub til et indlejret array?

Du kan referere til arrayet i underdokumentet "niveau1" ved hjælp af punktnotation. Så i stedet for at oprette indlejrede DBO-objekter, som du har gjort, skal du blot bruge:

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

Jeg skrev en test for at vise, at dette virker:

@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" ] } }
}



  1. MongoDB :hvor går grænsen mellem få og mange?

  2. Birt mongodb param

  3. hvordan man arbejder med flere handlinger og får tal ved hjælp af mongodb?

  4. Hvordan forespørger man MongoDB for at teste, om en vare eksisterer?