代码之家  ›  专栏  ›  技术社区  ›  Alok

在使用pymongo的mongodb中,upsert为true的update查询后如何返回记录字段?

  •  0
  • Alok  · 技术社区  · 6 年前

    我试图在MongoDB中插入记录,但我不想重复,所以我使用 update 命令与 upsert=true

    import pymongo
    client = pymongo.MongoClient(settings.MONGO_DB_URI)
    db = self.client[settings.MONGO_DB_NAME]
    filter = {
        'my_id': '1234',
        'name': 'alok'
    }
    record = {
        'my_id': '1234',
        'name': 'alok',
        'marks': 26
    }
    status = db['mycollection'].update(filter, {'$setOnInsert': record}, upsert=True)  
    print('id is ', status['my_id']) # this will not work but I want such behaviour
    

    只有在没有匹配筛选值的现有记录时,此代码才会插入记录。所以有两种情况:
    它将插入记录
    如果已经存在,则不会插入记录
    在这两种情况下我都想 my_id . 更新命令执行时,如何获取我的帐户ID?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jonski Goldstein    6 年前

    您可以搜索文档,然后打印出其ID

    print('id is ', db['mycollection'].find_one(filter)['my_id'])