0

I want to remove this

"lightControl" : 75

from this

{
"_id" : "dfdfwef-fdfd-fd94284o-aafg",
"name" : "Testing",
"serialNumber" : "fhidfhd8ghfd",
"description" : "",
"point" : {
    "type" : "Point",
    "coordinates" : [
        10.875447277532754,
        20.940549069378634
    ]
},
"ancestors" : [ ],
"metadata" : {
    "measurement" : {
        "high" : "40000.0",
        "medium" : "25000.0"
    },
    "digitalTwin" : {
        
    },
    "emails" : [
        ""
    ],
    "lastMeasurementDate" : "2010-03-04T11:32:06.691Z",
    "lightControl" : 75
},
"tags" : [ ],
"createdAt" : ISODate("2019-12-07T15:22:10.988Z"),
"updatedAt" : ISODate("2020-03-08T15:38:21.736Z"),
"_class" : "com.test.demo.api.model.Device"
}

All I want is for this specific id, to completely delete the lightControl element from metadata. I have tried $pull, but I am probably missing something. Any ideas? Thank you in advance!

2
  • 2
    "lightControl" is not an array element, it is just a field within an embedded document metadata - usually referred as as "metadata.lightControl". You just update the document using the $unset update operator on the field. Commented Mar 9, 2021 at 10:22
  • 1
    use $unset operator Commented Mar 9, 2021 at 10:39

1 Answer 1

1

Your lightControl is not in array, for nested property, use the dot wrapped in doublequotes:

MongoDB shell:

db.getCollection('yourCollectionName').update({},{$unset:{
    "metadata.lightControl":""
}})

In case you have a list of objects with _id(s) instead of updating directly, assume Node.js client for MongoDB is used:

// import mongodb from "mongodb"; // ES6
const mongodb = require("mongodb");

var client = MongoClient(...);
var coll   = client["yourDbName"]["yourCollectionName"];
var objs   = []; // <-- The array with _id(s)

for (let i=0; i<objs.length; i++){
    let id = mongodb.ObjectID(objs[i]["_id"]);

    coll.update({ _id:id },{$unset:{ "metadata.lightControl":"" }});
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.