2009-07-17 95 views
15

更新嵌套文件說我有一個數據結構是這樣的: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'] 
] 

當然,不是我在找的東西。

回答

14

下面的工作從我的mongo shell - 所以我不知道上面發生了什麼,你。試試看看它是否有效?如果是這樣的話,我會說抓住最新的mongo代碼,以防過去有問題。

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)。

+0

嗯,如實地我在python中進行這個測試,而不是在解釋器中。如果它與解釋器一起工作,則問題必須出現在我在python中的實現中。如果我仍然無法正常工作,我會去MongoDB論壇。 – defrex 2009-07-18 13:58:26