0

I asked on a previous question on how to find entries in a embedded MongoDB document. Sitting with a new issue now. My structure looks like :

{
    "_id" : ObjectId("5260c4bd95f8e3ad08000000"),
    "ip" : "127.0.0.1",
    "services" : [ 
        {
            "port" : "22"
        }
    ]}

I want to add a new key/value pair to services.port where the port is 22, so that it looks like this :

{
    "_id" : ObjectId("5260c4bd95f8e3ad08000000"),
    "ip" : "127.0.0.1",
    "services" : [ 
        {
            "port" : "22",
            "product" : "ssh"
        }
    ]}

This is the update I run :

db.hosts.update({ "ip" : "127.0.0.1" }, { $addToSet : { services : { "port" : "22", "product" : "ssh" }}});

And this is what I am getting

{
    "_id" : ObjectId("5260c4bd95f8e3ad08000000"),
    "ip" : "127.0.0.1",
    "services" : [ 
        {
            "port" : "22"
        }, 
        {
            "port" : "22",
            "product" : "ssh"
        }
    ]}

Anyone know what I am doing wrong? Should I delete the entry and recreate it?

1 Answer 1

2

$addToSet performs a $push operation if the element doesn't exist. Since { "port" : "22", "product" : "ssh" } doesn't already exist in the services array, a new document is pushed to services.

db.hosts.update({ "ip" : "127.0.0.1" }, { $set: { "services.0.product": "ssh" }});

This uses '0' to reference the first element of the services array and set its product property to "ssh". It works because arrays are also objects with each index position being a property/key.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.