0

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

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
Az Emna
  • 527
  • 2
  • 10
  • 26

3 Answers3

2

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
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
  • Getting the same result – Az Emna Jul 16 '19 at 15:33
  • The json file that i'm using [{ "_id": "5ad73dc9e17caf0014c5485f", "product": "5ad738a4e17caf0014c53922", "quantity": { "unit": "g", "value": 120 } }, { "_id": "5ad73dc9e17caf0014c54863", "product": "5aa1633d7e13440014db2a0f", "quantity": { "unit": "pièce (petite)", "value": 1 } }] – Az Emna Jul 16 '19 at 15:34
  • there no errors but i'm still getting the _id as a string not objectId – Az Emna Jul 16 '19 at 15:35
  • Try to remove _id because mongo auto generate id for you – Tony Ngo Jul 16 '19 at 15:35
  • i can't remove the _id cz it is related to other collections – Az Emna Jul 16 '19 at 15:36
2

You can change datatype. Give it a try.

db.mycollection.find().forEach(function(element){
  element._id = ObjectId(element._id);
  db.mycollection.save(element);
})
Malik Awan
  • 463
  • 5
  • 13
  • Ingredient.find(function(err, ingredients) { if (err) { console.log(err); } else { ingredients.forEach(element => { element._id = ObjectId(element._id); let ingredient = new Ingredient(element); ingredient .save() .then(ing => {}) .catch(err => {}); }); res.json(ingredients); } }); – Az Emna Jul 16 '19 at 21:53
1

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

Mohammad Yaser Ahmadi
  • 4,664
  • 3
  • 17
  • 39