Metafaniel
Metafaniel

Reputation: 30615

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

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?

Upvotes: 6

Views: 2963

Answers (3)

xiaohua Li
xiaohua Li

Reputation: 1

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

Upvotes: 0

MohanadAlnunu
MohanadAlnunu

Reputation: 1

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!

Upvotes: 0

Stefano Bretas
Stefano Bretas

Reputation: 51

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.

Upvotes: 5

Related Questions