Export from MongoDB Cloud into local MongoDB ("$oid is not valid for storage." error)
Asked Answered
C

3

6

I'm just learning about MongoDB. Is there an easy way to export/import data from MongoDB?

The task at hand is simple: Using MongoDB Cloud, copy a document from a collection (using the Copy Document button located in the Atlas > Collection section) and be able to import it into my local MongoDB DB. Doing so, I got the following:

{
  "_id": {"$oid":"5e666e346e781e0b34864de4"},
  "created_at":{"$date":{"$numberLong":"1583771188026"}}
}

Trying to import that into my local MongoDB using db.my_collection.insert() leads me to the following error:

WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 52,
                "errmsg" : "$oid is not valid for storage."
        }
})

So I've already done my research and I've found about how MongoDB creates output data in Extended JSON v2.0 (Relaxed mode) by default or in Canonical Mode.

So the documentation is really telling me the format that is used to export in MongoDB is not natively supported to be able to directly import it? What did I get wrong?

How can I import directly what is being exported?

Cystic answered 3/7, 2020 at 5:7 Comment(1)
Would mongoimport work for you?Briarwood
M
5

So... MongoDB doesn't support its own export format to import data into a collection. The solution for your problem would be just replacing

{
     "_id": {"$oid":"5e666e346e781e0b34864de4"},
     "created_at":{"$date":{"$numberLong":"1583771188026"}}
}

for:

{
     "_id": ObjectId("5e666e346e781e0b34864de4"),
     "created_at":{"$date":{"$numberLong":"1583771188026"}}
}

This way you'll be able to import your data without any problem.

Maieutic answered 28/8, 2020 at 18:53 Comment(1)
Facepalm hehe. I really wanted to be a way to do it. It seems to be this is the only way...Cystic
R
0

mongoDB uses Bson format to store it's data, you need to convert Json to Bson then import it. OR you can use mongoDBcompass and import your Json file and mongoDBcompass will do the job for you!

Reconcile answered 6/9, 2022 at 13:47 Comment(0)
O
0

I find another method to solve this problem.You can put this json file on your server and use mongodb command to load this json file into certain collection.An example are as followed: mongoimport --host localhost --port 27017 --username ezsonaruser --password 123456 --db ezsonar_25 --collection host_locations_test --file /root/shaql/host_locations.json

Outlay answered 8/11, 2022 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.