Amal Madawa
Amal Madawa

Reputation: 197

How to Insert Dynamic Fields to a Document In MongoDB Java Driver

 {
      "_id" : ObjectId("5888ae5f1495062544ac7951"),
      "site" : "gfhfh",
      "keywords" : {
        "keyword 1" : {
          "dailyranks" : {
            "2017-01-28" : {
              "rank" : 1,
            }
         **Dynamic data should add here by date ** 
          } 
        } 
      }
    }

I have tried to insert keyword rank by date. I want to add keyword rank each day. but it doesn't insert only update date and values. I have used following code in java.

for (DBObject dbo : result) {
            DBObject keywordlist = (DBObject) dbo.get("keywords");
            BasicDBObject a = new BasicDBObject();
            for (String keyword : keywordlist.keySet()) {
                DBObject rank = getRank();
                BasicDBObject rankdate = new BasicDBObject(date, rank);
                BasicDBObject aa = new BasicDBObject("dailyranks", rankdate);
                a.append(keyword, aa);
            }
            coll.update(dbo, new BasicDBObject("$set", new BasicDBObject("keywords", a)), true, false);
}

Upvotes: 0

Views: 799

Answers (1)

s7vr
s7vr

Reputation: 75934

Looks like you need an embedded array for both keywords and dailyranks.

"keywords": [{
    "keyword 1": {
        "dailyranks": [{
            "2017-01-28": {
                "rank": 1,
            }
        }]
    }
}]

After you have this structure, you'll use $push operator to insert new rank into embedded doc array.

You'll use $set if you trying to replace the entire embedded array.

Upvotes: 1

Related Questions