简体   繁体   中英

how can we append/update sub-document of collction in MongoDB using MongoDB Java driver?

My mongoDB document is as following.

{
  "_id": {
    "$oid": "551e34ddbb4fd7cc3a0849d0"
  },
  "192_168_100_12": [
    {
      "User_Login1": [
        {
          "time": {
            "$date": -23224339068000
          },
          "message": "leneghadik"
        }
      ]
    },
    {
      "User_Login": [
        {
          "time": {
            "$date": -23224339068000
          },
          "message": "leneghadik"
        }
      ]
    },
    {
      "User_Login": [
        {
          "time": {
            "$date": -23224339068000
          },
          "message": "my ja"
        }
      ]
    },
    {
      "User_Login1": {
        "time": {
          "$date": -23224339068000
        },
        "message": "my ja"
      }
    }
  ]
}

I want to append new object into "User_Login1" using java. How can i achieve that? I tried many method but it didn't work and i end up appending data into "192_168_100_12" .

My code for appending was as below.

BasicDBObject event = new BasicDBObject("time", curDate).append("message", "my ja");
node_info.update(new BasicDBObject(), new BasicDBObject("$push", new BasicDBObject("192_168_100_12", new BasicDBObject("User_Login1", event))));

Please help me.

BasicDBObject event = new BasicDBObject("time", curDate).append("message", "my ja");
BasicDBObject data = new BasicDBObject("$push", 
                               new BasicDBObject("192_168_100_12$User_Login1", event));
collection.update(new BasicDBObject(), data);

This will probably do your work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM