首页 > 解决方案 > Using $set to update a document's value with key containing a dot(.), MongoDB

问题描述


I have this very basic collection (blog.posts) from which I want to update the value of a key (author.name) using the $set modifier. Here is a sample of a document from the collection:

{
        "_id" : ObjectId("5ca66e7d8a3bb6e58e0d85f4"),
        "s_id": "unique_post",
        "title" : "MongoDB is cool",
        "author.name" : "Terence"
}

I want to change the value of the author.name key from Terence to Benjamin and this is the query with which I'm trying to acheive the result:

db.blog.posts.update({"s_id": "unique_post"}, {"$set":{"author.name":"Benjamin"}})

The issue is that when I execute this query, I end up with a new nested ducument as shown:

{
        "_id" : ObjectId("5ca66e7d8a3bb6e58e0d85f4"),
        "title" : "MongoDB is cool",
        "author.name" : "Terence",
        "author" : {
                "name" : "Benjamin"
        }
}

I know that this is to be expected but my question is: How do I modify a value in a document who's key contains a dot(.) ?
Please I'm new to mongoDB and any other tips would be highly appreciated.

标签: mongodb

解决方案


As per MongoDB documentation dot(.) is a restricted character in field names. So you cannot have dot(.) in field names. That is the reason it converts the dot(.) value into subdocument.

enter image description here


推荐阅读