How to use $unset
when a key contains dots in its name?
const key = "test"
const result = await db.collection(collection).updateOne(
{ [key]: { $exists: true } },
{ $unset: { [pathToKey]: 1 } }
);
given this document:
{
"test": {
"a": "b", // <- test.a successfully erases the 'a' key
"v0.0.1": "ok" // <- test.v0.0.1 fails
}
}
when pathToKey
is 'test.a'
it successfully erases the a
key
when it 'test.v0.0.1'
it fails, probably because the key contains a .
in its name
I’m using the latest Mongo version
https://mongoplayground.net/p/Chiy7DtIqWb
I also tried using $unsetField
: https://mongoplayground.net/p/MNyfhh1vdDW
2
Answers
The keys with dots are not supported by MongoDB
http://docs.mongodb.org/manual/reference/limits/#Restrictions-on-Field-Names
Maybe you could use a workaround but i think it will be better to use different keys
You can use
$setField
with$$REMOVE
Mongo Playground
For a nested object, chain up the above solution with
$mergeObjects
Mongo Playground