1

I have exported one of my collections from MongoDB and it looks like the following:

[
{
    "_class": "test.Tag",
    "title": "My Title",
    "_id": {
        "$oid": "637a2bc4a9c297b306dd0be9"
    }
}
]

Now, I want to add another item to this collection. I have created a json file exactly in the same format. However, when I use the following command:

db.tag.insertMany([{"_class": "test.Tag",  "title": "New Title","_id": {"$oid": "637a4171833047f9e046f3c9"}}])

I get the error:

MongoBulkWriteError: _id fields may not contain '$'-prefixed fields: $oid is not valid for storage.

I found a couple of similar questions on stackoverflow, e.g. this one, but they didn't help me.

How should I insert something in my database? When I use MongoDB Compass, there is no problem. It works. But when I try it on my real database on the server, it doesn't work. If it helps, I am using Mongo version 6.0.1.

Your help would be appreciated.

user13578
  • 107
  • 9
  • Try `db.tag.insertMany([{"_class": "test.Tag", "title": "New Title","_id": ObjectId("637a4171833047f9e046f3c9")}])` – nimrod serok Nov 20 '22 at 17:17
  • @nimrodserok I had tried that, but I get "SyntaxError: Unexpected token" at the end of my input. – user13578 Nov 20 '22 at 17:29
  • Which tool do you use to insert the data? – Wernfried Domscheit Nov 20 '22 at 18:01
  • @WernfriedDomscheit I actually use just Windows CMD. I connect to my server using SSH and then by run commands like "docker exec -it mongodb mongosh --port 27017 -u "user" -p "password" --authenticationDatabase "admin"", then "use myDatabase" and then I try to run the above command to insert something into my database. – user13578 Nov 20 '22 at 18:10

1 Answers1

0

In the legacy mongo shell there is no helper for extended json format , but in mongosh you can use EJSON to deserialize the extended json and insert it as follow:

    > db.test4.insertMany([EJSON.deserialize(  {"_id": {   "$oid": "637aa8243d58f36141e59c8d"} } )])
    {
     acknowledged: true,
     insertedIds: { '0': new ObjectId("637aa8243d58f36141e59c8d") }
    }
    >

( The legacy mongo shell was deprecated in MongoDB 5.0 and removed in MongoDB 6.0 )

R2D2
  • 9,410
  • 2
  • 12
  • 28