【问题标题】:how to add fields in google cloud fire store using python如何使用 python 在 Google Cloud Firestore 中添加字段
【发布时间】:2019-07-18 02:12:48
【问题描述】:

我有两个 Json 数据数据 1 和数据 2,当我尝试合并两个 dicts 时,我想将它合并到 fire store 文档中,只有一半显示。

data = {
    u'name': u'Los Angeles',
    u'state': u'CA',
    u'country': u'USA'
}
data2= {
    u'name': u'MIAMI',
    u'state': u'CA',
    u'country': u'USA'
}

db.collection(u'cities').document(u'LA').set(data)



city_ref = db.collection(u'cities').document(u'LA')

city_ref.set({
    u'name': u'MIAMI',
    u'state': u'CA',
    u'country': u'USA'
}, merge=True)

 #only this part is showing
  {
    u'name': u'MIAMI',
    u'state': u'CA',
    u'country': u'USA'
}
   #when i, doing this
  data = {
    u'name': u'Los Angeles',
    u'state': u'CA',
    u'country': u'USA',
    u'name': u'MIAMI',
    u'state': u'CA',
    u'country': u'USA'}
    #only this much part is showing in my field
    u'name': u'MIAMI',
    u'state': u'CA',
    u'country': u'USA' 

有没有办法在python中合并这两个

【问题讨论】:

    标签: python json database firebase google-cloud-firestore


    【解决方案1】:

    每个字段名称只能有一个值。当您想向同一文档添加其他字段时,合并很有用,例如:

     data = {
        u'name': u'Los Angeles',
        u'state': u'CA',
        u'country': u'USA'
    }
    
    db.collection(u'cities').document(u'LA').set(data)
    
    city_ref = db.collection(u'cities').document(u'LA')
    
    city_ref.set({
        u'name2': u'MIAMI',
        u'state2': u'CA',
        u'country2': u'USA'
    }, merge=True)
    
    # Result
    
    data = {
        u'country': u'USA',
        u'country2': u'USA',
        u'name': u'Los Angeles',
        u'name2': u'MIAMI',
        u'state': u'CA',
        u'state2': u'CA',}
    

    【讨论】:

      【解决方案2】:

      您可以使用此代码(如果它们不存在,它将添加新字段,如果它们已经存在则更新它们)。

      doc.reference.update({
                      u'newField1': newValue1
                      u'newField2': newValue2
                  })
      

      【讨论】:

        猜你喜欢
        • 2021-07-19
        • 2020-07-29
        • 2020-04-25
        • 2021-08-03
        • 2018-11-18
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 2020-06-05
        相关资源
        最近更新 更多