Update value in array of string on array of objects mongodb - arrays

I'm trying to update a value of a array of strings in mongodb, which is inside of another array of objects
here is an example of the model
{
"_id" : ObjectId("5a8cd02f87d4839d279f6559"),
"category" : "0",
"email" : "doctor#doctor.com",
"password" : "doctor",
"name" : "doctor",
"directorys" : [ {
"path" : "doctor#doctor.com/own/",
"files" : [ "" ]
},
{
"path" : "doctor#doctor.com/modified/",
"files" : [ "" ]
},
{
"path" : "doctor#doctor.com/own/pacient1",
"files" : [ "", "README.txt" ]
}
] }
}
So im trying to update the name "README.txt" to "README2.txt" but i'm struggling with mongo
i tried this
db.users.update({"email":"doctor#doctor.com","directorys.files":"README.txt"},{"$set":{"directorys.files.$":"README2.txt"}})
but throws the following error
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "cannot use the part (directorys of directorys.files.2) to traverse the element ({directorys: [ { path: \"doctor#doctor.com/own/\", files: [ \"\" ] }, { path: \"doctor#doctor.com/modified/\", files: [ \"\" ] }, { path: \"doctor#doctor.com/own/pacient1\", files: [ \"\", \"README.txt\" ] } ]})"
}
})
what i am missing? i dont know what to do

Since directorys is an array, I think you need an array operator there as well. Try this query:
db.users.update(
{"email":"doctor#doctor.com","directorys.files":"README.txt"},
{"$set":{"directorys.$[selectedFiles].files.$":"README2.txt"}},
{arrayFilters: [{"selectedFiles.files": "README.txt"}]}
)
You can see more about arrayFilters here:
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#up.S[]
ArrayFilters allows you to take an array, select only those elements that match a certain criteria, and then apply $set (or any other update / upsert operator) to just those elements.
One thing though is that this will only update the first element of your files array that has README.txt. If README.txt is present more than once, you won't update all of them. If you want to update all elements in the array that are README.txt, you need a second arrayFilter, like this:
db.users.update(
{"email":"doctor#doctor.com","directorys.files":"README.txt"},
{"$set":{"directorys.$[selectedDirs].files.$[selectedFiles]":"README2.txt"}},
{arrayFilters: [{"selectedDirs.files": "README.txt"}, {"selectedFiles": "README.txt"}]}
)
That should select all directorys elements with a files array that has at least one README.txt, then select all elements within that files array that equals README.txt, and then set those elements to README2.txt.

Well i could update the element in the array doing the following command
db.users.update({"directorys.files":"README.txt","email":"doctor#doctor.com"},{"$set":{"directorys.$.files.1":"README2.txt"}})
I have to do some server side work to get that number "1" dinamycally but that resolves my question.
I got inspiration from here https://dba.stackexchange.com/questions/114329/mongodb-update-object-in-array

Related

How to delete particular no of elements from array in mongodb

I have collection as below
"_id" : "PS8720_18",
"AlertID" : "18",
"Status" : "ACTIVE",
"triggerHistory" : [
{"triggerId" : "1535081507421"},
{"triggerId" : "1535105196735"},
{"triggerId" : "1535341330335"},
{"triggerId" : "1535364578821"}
]
I want to delete all element and just want keep last two entries in the array. Each document has different no of elements in array. How do I achieve this?
Please Check with the following Query
db.getCollection('youtablename').update({}, {
$push: {
triggerHistory: {
$each: [ ],
$slice: -2
}
}},{multi:true})
Hope it Helps !!

MongoDB - Updating subdocument

I'm working with mongo 3.4.13 and I want to add an element in this document:
{
"_id" : ObjectId("5981d38cf43047f3235febbc"),
"code" : "A0001",
"subItems": [
{
"_id" : ObjectId("5981d38cf43047f3235febbc"),
"code" : "A1001",
"subItems": []
},
{
"_id" : ObjectId("5981d38cf43047f3235febbc"),
"code" : "A2001",
"subItems": [
{
"_id" : ObjectId("5981d38cf43047f3235febbc"),
"code" : "A2101",
"subItems": [
//I wanna add an element here
]
}
]
}
]
}
But I have no idea how to do it, any idea?
According to description as mentioned into above question I assume that you need to add an element into subItems array field belonging to BSON Document as mentioned above.
$addToSet operator is used to append a value into an array field as a part of update operation only if value does not exist into an array thereby ensuring uniqueness of values into an array field.

MongoDB - Pull multiple objects from an array

Hi I'm trying to remove multiple objects from an array that looks like this.
{
"_id" : ObjectId("5a7da1bda21d5f3e8cf005b3"),
"owner" : "1",
"group_name" : "PAASCU Board",
"group_members" : [
{
"faculty_name" : "Cheska Dela Rosa",
"faculty_number" : 2,
"_id" : ObjectId("5a7da1bda21d5f3e8cf005b5")
},
{
"faculty_name" : "Earl Sempio",
"faculty_number" : 7323,
"_id" : ObjectId("5a7da1bda21d5f3e8cf005b4")
},
{
"faculty_number" : 203,
"faculty_name" : "Sample",
"_id" : ObjectId("5a7dbf7952bd150a94d83958")
},
{
"faculty_number" : 8025,
"faculty_name" : "Sample Postman",
"_id" : ObjectId("5a7dc64a1cf5dd3d50167d53")
}
],
"__v" : 0 }
It works when I remove a single object using the $pull with this code.
db.getCollection('groups').update({_id: ObjectId("5a7da1bda21d5f3e8cf005b3")}, {$pull: {"group_members": {"faculty_number":8025}}})
But what if I want to remove multiple objects with different faculty_number? I tried using the $each method just like how I add multiple objects in the array but it doesn't work well.
Use $in operator to pass the list of faculty values to remove documents from embedded array. More here
Try
db.groups.update(
{"_id": ObjectId("5a7da1bda21d5f3e8cf005b3")},
{"$pull":{"group_members":{"faculty_number":{$in:[8025,7323]}}}}
)

Query collection containing BsonArray

Sorry, first time trying mongo.
Given the following data ...
db.masterList.findOne()
{
"_id" : ObjectId("59d128805b19310ac8ab3fc2"),
"MasterDefinition" : {
"Location" : [
"Whole House",
"Master Bedroom",
"Hallway 2"
],
"DeviceType" : [
"Receptacle",
"GFI",
"LED dimmer"
],
"Style" : [
"Decora",
"Standard"
],
"Color" : [
"White",
"Light Almond"
]
}
}
How do I retrieve the contents of the Color array? I expect something like
["White","Light Almond"]
How do I list the 4 arrays directly subordinate to MasterDefintion? I expect to see
["Location","DeviceType","Style","Color"]
Thanks
For the first part, you can simply do a
collection.aggregate({
$project: {
"_id": 0, // exclude the "_id" field from the result
"result": "$MasterDefinition.Color"
}
})
The second part requires a little magic (documentation can be found here: aggregation framework, $project, $objectToArray):
collection.aggregate({
$project: {
"temp": {
$objectToArray: "$MasterDefinition" // transform the "MasterDefinition" subdocument into an array
}
}
}, {
$project:{
"_id": 0, // do not include the "_id" field in the result - this is an optional step
"result": "$temp.k" // only get the keys (as in "k" fiels) from the array
}
})
How do I retrieve the contents of the Color array? I expect something like ["White","Light Almond"]
// the first argument here is a filter, the second argument is a projection
// since you specified no filter I have only included a projection
// this projection tells MongoDB to return the Color subdocument
// from within the MasterDefinition sub document
db.getCollection('masterList').find({}, {'MasterDefinition.Color': 1})
The above command will return:
{
"_id" : ObjectId("59d128805b19310ac8ab3fc2"),
"MasterDefinition" : {
"Color" : [
"White",
"Light Almond"
]
}
}
How do I list the 4 arrays directly subordinate to MasterDefintion? I expect to see ["Location","DeviceType","Style","Color"]
This is a bit trickier because "Location","DeviceType","Style","Color" are not elements in an array instead they are the names of attributes in the MasterDefinition subdocument. You can use the $objectToArray aggregation operator to turn these attribute names into an array but the resulting document doesn't looks exactly like what you hoped for. Here's an example ...
db.getCollection('masterList').aggregate([
// creates an array named "categories" from the attributes of the MasterDefinition sub document
{ $project: { categories: { $objectToArray: "$MasterDefinition" } } },
// projects on the keys of the "categories" array
{$project: {'categories.k': 1}}
])
... which produces this output:
{
"_id" : ObjectId("59d128805b19310ac8ab3fc2"),
"categories" : [
{
"k" : "Location"
},
{
"k" : "DeviceType"
},
{
"k" : "Style"
},
{
"k" : "Color"
}
]
}

How to update an array of multiple elements in mongodb..?

I have a requirement to update an array of multiple elements.My collections is in the following way
{
"_id" : ObjectId("53e87e239ae974e6a0a81004"),
"name" : "mulagala",
"notifications" : [
{
"name" : "apple",
"status" : 0
},
{
"name" : "microsoft",
"status" : 0
},
{
"name" : "android",
"status" : 0
}
]
}
now i want to change the every status element of the array should be changed to 1, ie.status:1 with a single query.
I tried in the following way
db.mystatus.update({'notifications.status':0},{$set:{'notifications.$.status':1}},false,true)
But the first record only updating, what to do.Any help would be appriciated!
Have you tried updating the elements of the array using the $ operator for arrays? Currently it updates only one element as the index is coded to 0.

Resources