Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: use MongoImport with csv to update single field only

Tags:

mongodb

I am trying to update a single field in each document in my collection using a csv and Mongoimport with –upsert included. However the process removes all other fields in the document.

I have a Books Collection with documents like:

{

    "_id" : "knOIv8ZUUK", 
    "Price" : 2.2, 
    "Title" : "Rats Ahoy"
}

{

    "_id" : "okYEGuWznv", 
    "Price" : 3.3, 
    "Title" : "Friendly Fish"
}

a csv file:

_id,Price

knOIv8ZUUK,2.2

okYEGuWznv,3.3

And import using:

mongoimport  --db local  --collection Books --upsert  --type csv  
             --headerline  --file c:\import\newPrice

With results deleting the Title field

{ 

    "_id" : "knOIv8ZUUK", 
    "Price" : 2.2
}

{ 

    "_id" : "okYEGuWznv", 
    "Price" : 3.3
}

I, incorrectly, thought Upsert would just update an imported field. So is there another process I can use to update just 1 field in large number of documents? thanks

like image 912
MarkM Avatar asked Sep 06 '25 23:09

MarkM


2 Answers

From mongoimport --upsertFields doc You can need to use mode merge:

Merge existing documents that match a document in the import file with the new document. mongoimport will insert all other documents. Merge Matching Documents during Import describes how to use --mode merge.

and specify the field name, default is '_id'

--mode merge --upsertFields <fieldname>

so for your case just

--mode merge --upsertFields
like image 194
Fan Avatar answered Sep 11 '25 06:09

Fan


New feature has been added since version 3.4 Documentation here.

Check this option

--mode insert|upsert|merge

In your case you can use this may be:

--mode merge
like image 37
neel Avatar answered Sep 11 '25 07:09

neel