Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Set server status to inactive in a MongoDB collection with server records?
To set a server status to inactive in a MongoDB collection, use the positional operator $ with the $set update operator to target specific array elements based on matching criteria.
Syntax
db.collection.update(
{ "arrayField.matchField": "matchValue" },
{ $set: { "arrayField.$.updateField": "newValue" } }
);
Sample Data
Let us create a collection with server records −
db.demo707.insertOne({
id: 101,
"serverInformation": [
{
"IP": "192.56.34.3",
"Status": "Active"
},
{
"IP": "192.56.36.4",
"Status": "Inactive"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ea6f852551299a9f98c93c8")
}
Display all documents from the collection −
db.demo707.find();
{
"_id": ObjectId("5ea6f852551299a9f98c93c8"),
"id": 101,
"serverInformation": [
{ "IP": "192.56.34.3", "Status": "Active" },
{ "IP": "192.56.36.4", "Status": "Inactive" }
]
}
Example: Set Active Server to Inactive
Update the server with IP "192.56.34.3" from "Active" to "Inactive" status −
db.demo707.update(
{ "serverInformation.IP": "192.56.34.3" },
{ $set: { "serverInformation.$.Status": "Inactive" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display the updated document −
db.demo707.find();
{
"_id": ObjectId("5ea6f852551299a9f98c93c8"),
"id": 101,
"serverInformation": [
{ "IP": "192.56.34.3", "Status": "Inactive" },
{ "IP": "192.56.36.4", "Status": "Inactive" }
]
}
Conclusion
Use the positional operator $ to update specific array elements in MongoDB. The query matches the array element by IP address, and $set updates the Status field of that matched element to "Inactive".
Advertisements
