복붙노트

[MONGODB] MongoDB의에서 중첩 된 문서를 업데이트

MONGODB

MongoDB의에서 중첩 된 문서를 업데이트

나는이 같은 데이터 구조 뭔가를 말 :

{
    'name': 'test',
    'anotherdoc': {
        'something': 'someval',
        'somenum': 1
    }
}

지금, 나는이 세트 뭔가 싶어 말한다. 처음에 나는 그것이과 같이 할 것이라고 생각 :

collection.update({'_id': myid}, {$set: {'anotherdoc.something': 'somenewval'});

그러나 이것은 잘못된 것 같다. 그것은 거기에 일부 데이터를 넣어 않지만, 이상한 방식으로 그렇게한다. 그것은,이 경우에는과 같이 끝낼 것이다 :

[
    {
        'name': 'test',
        'anotherdoc': {
            'something': 'someval',
            'somenum': 1
        }
    },
    ['anotherdoc.something', 'someval']
]

물론, 내가 찾고 있었던되지 것.

해결법

  1. ==============================

    1.몽고 쉘에서 나를 위해 다음 작품은 - 잘 모르겠어요 그래서 당신을 위해 위에서 무슨 일이 있었는지. 이 시도하고 그것이 작동하는지? 나는 문제가 될하는 데 사용되는 경우 뭔가의 최신 몽고 코드를 잡아 말할 수 있도록합니다.

    몽고 쉘에서 나를 위해 다음 작품은 - 잘 모르겠어요 그래서 당신을 위해 위에서 무슨 일이 있었는지. 이 시도하고 그것이 작동하는지? 나는 문제가 될하는 데 사용되는 경우 뭔가의 최신 몽고 코드를 잡아 말할 수 있도록합니다.

    x = { 'name': 'test', anotherdoc: { 'something': 'someval', somenum : 1 } }
    > x
    {"name" : "test" , "anotherdoc" : {"something" : "someval" , "somenum" : 1}}
    > collection = db.foo;
    test.foo
    > collection.insert(x)
    > collection.find()
    {"_id" :  ObjectId( "4a61b6711591f41f0f1bc5ff")  , "name" : "test" , "anotherdoc" : {"something" : "someval" , "somenum" : 1}}
    > x
    {"name" : "test" , "anotherdoc" : {"something" : "someval" , "somenum" : 1}}
    > x._id
    > x = collection.findOne()
    {"_id" :  ObjectId( "4a61b6711591f41f0f1bc5ff")  , "name" : "test" , "anotherdoc" : {"something" : "someval" , "somenum" : 1}}
    > collection.update({'_id': x._id}, {$set: {'anotherdoc.something': 'somenewval'}} )
    > collection.find()
    {"_id" :  ObjectId( "4a61b6711591f41f0f1bc5ff")  , "name" : "test" , "anotherdoc" : {"somenum" : 1 , "something" : "somenewval"}}
    > 
    

    전술 한 바와 같이, MongoDB의 포럼은 아마 더 빨리 (또는 시도의 IRC)를 들키지.

  2. ==============================

    2.당신은 더 나은 MongoDB를 사용자의 googlegroup이 물어 것입니다. 귀하의 질문에 대한 대답은 여기 http://groups.google.com/group/mongodb-user/msg/583d37ef41ef5cca?hl=en입니다

    당신은 더 나은 MongoDB를 사용자의 googlegroup이 물어 것입니다. 귀하의 질문에 대한 대답은 여기 http://groups.google.com/group/mongodb-user/msg/583d37ef41ef5cca?hl=en입니다

  3. from https://stackoverflow.com/questions/1145956/updating-nested-documents-in-mongodb by cc-by-sa and MIT license