I have been wrestling with trying to import JSON – using mongoimport or the Javascript insert/replace calls – an array of mongo ObjectIds.
According to Mongo docs, to specify a Mongo Id in JSON, one uses {“$oid”:XXXX}.
The long and short of it is that if the data is in a JSON array, the mongo import – both command line and API – does not recognize {“$oid”:XXXX} and convert it to an Object Id.
Below is a test case, using Compass as the viewer, and what I see is the array members are not recognized as ObjectIds. I have no idea if this is a bug, or a feature. It even manifests itself with JSON.stringify.
Given a test case where we insert the JSON below
{
"_id": {"$oid": "fa3e6fe626f94cdfe8558a6e"},
"members1": [
{"$oid:": "6d51c5346c5060a572c4cbc7"},
{"$oid:": "fe8ce32ad418303ed38aec47"},
{"$oid:": "9d4076461b20770443d46327"},
{"$oid:": "28b730141139503b00128eb4"}
],
"members2": {
"1": {"$oid": "6d51c5346c5060a572c4cbc7"},
"2": {"$oid": "fe8ce32ad418303ed38aec47"},
"3": {"$oid": "9d4076461b20770443d46327"},
"4": {"$oid": "28b730141139503b00128eb4"}
},
"embed1": {"2": {"$oid": "fe8ce32ad418303ed38aec47"},
"_id": {"$oid": "6d51c5346c5060a572c4cbc7"}
},
"embed2": {"type": "vessel-status",
"lookupValue": "A",
"description": "Active",
"isActive": true,
"isAshop": true,
"isWcgop": true,
"_id": {"$oid": "6d51c5346c5060a572c4cbc7"}
},
"parent": {"$oid": "d9630c927bc17266f4549426"}
}
When we retrieve the data we get:
t> db.resources.findOne(ObjectId('fa3e6fe626f94cdfe855
8a6e'))
{
_id: ObjectId("fa3e6fe626f94cdfe8558a6e"),
members1: [
{ '$oid:': '6d51c5346c5060a572c4cbc7' },
{ '$oid:': 'fe8ce32ad418303ed38aec47' },
{ '$oid:': '9d4076461b20770443d46327' },
{ '$oid:': '28b730141139503b00128eb4' }
],
members2: {
'1': ObjectId("6d51c5346c5060a572c4cbc7"),
'2': ObjectId("fe8ce32ad418303ed38aec47"),
'3': ObjectId("9d4076461b20770443d46327"),
'4': ObjectId("28b730141139503b00128eb4")
},
embed1: {
'2': ObjectId("fe8ce32ad418303ed38aec47"),
_id: ObjectId("6d51c5346c5060a572c4cbc7")
},
embed2: {
type: 'vessel-status',
lookupValue: 'A',
description: 'Active',
isActive: true,
isAshop: true,
isWcgop: true,
_id: ObjectId("6d51c5346c5060a572c4cbc7")
},
parent: ObjectId("d9630c927bc17266f4549426")
}