简体   繁体   中英

MongoDB insert and update Field

In my MongoDB collection I have some fields, one of them is "EntitySet, now I need to insert a new field, for example "EntityAlchemy" to it.

This is how it looks now:

"EntitySet": [ 
    {
            "Name" : "maka",
            "EntityType" : "Person",
            "Relevance" : 0.0,
            "SentimentScore" : 0.0,
            "CountInText" : 0
    }
]

and it should look like these after the update

"EntitySet" : [ 
    {
        "Name" : "maka",
        "EntityType" : "Person",
        "Relevance" : 0.0,
        "SentimentScore" : 0.0,
        "CountInText" : 0
    }
],
"EntityAlchemy" : [ 
    {
        "Name" : "DZ Bank",
        "EntityType" : "Company",
        "Relevance" : 0.0,
        "SentimentScore" : 0.0,
        "CountInText" : 0
    }
]

I can only find how to update an existing field. Can someone help how to do this?

Use $set for adding more key-value pairs.

Syntax is:

db.collection.update({query}, {$set: {key-value pairs}});

Example:

db.coll1.update({_id:1}, 
   {$set: "EntityAlchemy" : [ 
     {
      "Name" : "DZ Bank",
      "EntityType" : "Company",
      "Relevance" : 0.0,
      "SentimentScore" : 0.0,
      "CountInText" : 0
      }
     ]});

You can use $push for array, mongo will create the field as array if it does not exists.

var alchemy = {
        "Name" : "DZ Bank",
        "EntityType" : "Company",
        "Relevance" : 0.0,
        "SentimentScore" : 0.0,
        "CountInText" : 0
    };
db.getCollection('test').update({_id:1},{$push : {'EntityAlchemy' : alchemy}});

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