Import json Mongodb

So i imported a json file with

mongoimport -d mydb -c mycollection --jsonArray < glossary.json
the problem is that _id is stored as string in Db and not as an ObjectID

Like this

enter image description here

So when i try to execute findbyId/findOne({_id:id}) request i get a null as a result
I’ve tried the solution with findOne({ _id: new ObjectID(id) } but it didn’t work for me

PS: the _id in the json file is a string also
is there is any way to convert _id from string to objectId or any other solution

Sorry if the question is duplicate

14 thoughts on “Import json Mongodb”

  1. You can change datatype. Give it a try.

      element._id = ObjectId(element._id);;
  2. you can open the .json file into the text Editor like vsCode and replace id to objectId(id) with regex like this:

    enter image description here

    so find : _id: (".*")

    and replace with : _id: ObjectId($1)

    after that import your data into the database

  3. Try these command to see if it work

    mongoimport --db dbName --collection collectionName --file fileName.json --jsonArray
    mongoimport --db test --collection user --drop --file /path/user.json

Leave a Comment