MarkM
MarkM

Reputation: 53

MongoDB: use MongoImport with csv to update single field only

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

Upvotes: 4

Views: 5223

Answers (2)

Fan
Fan

Reputation: 31

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

Upvotes: 3

neel
neel

Reputation: 391

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

Upvotes: 1

Related Questions