2014-11-21 102 views
1

创建嵌套数组的对象这是我收集的MongoDB - 更新或Pymongo

{ 
    "_id" : '50001', 
    "data" : 
     [ 
      { 
        "name" : "ram", 
        "grade" : 'A' 
      }, 
      { 
        "name" : "jango", 
        "grade" : 'B' 
      }, 
      { 
        "name" : "remo", 
        "grade" : 'A' 
      } 
     ] 
} 

这里我要更新对象对应于“名”:“詹”,并必须建立一个新项数组如果“jango”不存在。

我可以创建一个新条目但在“创建或更新”中失败。

我试过这种方式蒙戈解释

db.MyCollection.update({'_id': '50001', "data.name" :"jango"}, {'$set':{'data': {'data.$.grade':'A'}}}, upsert=true) 

但显示

not okForStorage 

回答

0

你几乎有:

db.YourCollection.update(
    { '_id':'50001', <-- to find document 
    'data.name': 'jango' < -- to find element of the array 
    }, 
    { '$set': { "data.$.grade" : 'A' } } <-- with .$ you reference array element from first argument 
) 

Link to documentation

+1

但我只需要创建一个像{“名”的新条目:“詹”,“品位” :'A'},如果我搜索的名字不在那里。 – ManikandanV 2014-11-21 14:21:52

0

蒙戈嵌套的UPDATE啊,你应该知道的位置或$更新值的下方可以帮助

db.collecionName.update(
    {'_id': '50001', "data.name" :"jango"}, 
    {'$set':{'data.1.grade':'A'}}, upsert=true) 

db.collecionName.update(
    {'_id': '50001', "data.name" :"jango"}, 
    {'$set':{'data.$.grade':'A'}}, upsert=true) 
+0

但我需要搜索而不考虑数组索引。只有我能够知道这个名字。 – ManikandanV 2014-11-21 14:25:01

+0

如果搜索名称不存在,这将不会创建新的条目。 – ManikandanV 2014-11-21 14:29:43

+0

为此,你应该尝试mongo地图减少它会帮助你。 – Yogesh 2014-11-21 14:44:46