Mongoimport csv files with string _id and upsert

后端 未结 5 1994
清歌不尽
清歌不尽 2021-01-13 05:26

I\'m trying to use mongoimport to upsert data with string values in _id. Since the ids look like integers (even though they\'re in quotes), mongoimport treats them as intege

5条回答
  •  执笔经年
    2021-01-13 05:56

    Unfortunately there is not now a way to force number-like strings to be interpreted as strings:

    https://jira.mongodb.org/browse/SERVER-3731

    You could write a script in Python or some other language with which you're comfortable, along the lines of:

    import csv, pymongo
    
    connection = pymongo.Connection()
    collection = connection.mydatabase.mycollection
    reader = csv.DictReader(open('myfile.csv'))
    for line in reader:
        print '_id', line['_id']
        upsert_fields = {
            '_id': line['_id'],
            'my_other_upsert_field': line['my_other_upsert_field']}
    
        collection.update(upsert_fields, line, upsert=True, safe=True)
    

提交回复
热议问题