1

My collection has this structure:

{
    "_id" : "7ZEc8dkbs4tLwhW24",
    "title" : "title",
    "json" :

        {
            \"cells\":[
                {
                    \"type\":\"model\",
                    \"size\":{\"width\":100,\"height\":40},
                    \"id\":\"11dc3b6f-2f61-473c-90d7-08f16e7d277a\",
                    \"attrs\":{
                        \"text\":{\"text\":\"content\"},
                        \"a\":{\"xlink:href\":\"http://website.com\",\"xlink:show\":\"replace\",\"cursor\":\"pointer\"}
                    }
                }
            ]
        }
}

Now I need to insert/update the field json.cells.attrs.a in my meteor app. All informations I got are _id (document ID) and id (id of element in cells). If a doesn't exist, the element should be created.

My attempt is not correct, as the query isn't looking for the elemID to get the correct element in the cells-array:

var linkObject = {"xlink:href":"http://newURL.com","xlink:show":"replace","cursor":"pointer"};
var docID = '7ZEc8dkbs4tLwhW24';
var elemID = '11dc3b6f-2f61-473c-90d7-08f16e7d277a'; // How to search for this 'id'?

var result = Collection.findOne({ _id: docID });
var json = JSON.parse(result.json);

// find id = elemID in 'json'
// add/update 'a'

// update json in mongoDB document

1 Answer 1

1

In your code you are only adding the docID as criteria in your query. You must add the elemID to your query criteria. Then after that you can use dot.notation and the $(Positional Operator) to update the a property of the attrs object. You can do it like this:

Collection.update(
    {"_id" : docID , "json.cells.id" : elemID },
    {$set: { "json.cells.$.attrs.a" : linkObject}}
}

$set, will create the field if the field does not exist. You can use the $ Positional Operator if you don't know the array position.

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

8 Comments

What does false and true mean?
Check out my edited answer, but they were options. You can see how to add options in mongo > 2.6 here: docs.mongodb.org/manual/reference/method/db.collection.update/…
db.collection.find({"_id" : '7ZEc8dkbs4tLwhW24' , "json.cells.id" : '11dc3b6f-2f61-473c-90d7-08f16e7d277a' }).pretty() doesn't give me any result.
I just see that in the DB the data looks like: "json" : "{\"cells\":[... I think the slashes inside of json make some trouble, right?
in the mongodb shell can you post how your data looks when you run. db.collection.find({"_id" : "7ZEc8dkbs4tLwhW24")})
|

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.