MongoDB update $ update operator with multiple array selector - arrays

I'm trying to update an element inside an array using the $ update operator. The document contains 2 array fields and I have to query both to select the correct document.
The collection is called locations and the document looks like this:
{
"_id" : "XqEQYpitGFG3nnf3C",
"wallpapers" : [
{
"_metadata" : {
"master" : "vwb22W4MhkqtvAp89",
"isMaster" : false
},
"role" : "master",
"_id" : ""
},
{
"_metadata" : {
"master" : "vwb22W4MhkqtvAp89",
"isMaster" : false
},
"role" : "clone",
"_id" : ""
},
{
"_metadata" : {
"master" : "vwb22W4MhkqtvAp89",
"isMaster" : false
},
"role" : "pod",
"_id" : ""
}
],
"ancestors" : [
"vwb22W4MhkqtvAp89",
"tqzqfum9uMs47xcHW",
"b4d83aqTkq6TGvXts",
"XqEQYpitGFG3nnf3C"
]
}
The update operator looks like this:
db.getCollection('locations').update(
{
"ancestors": "b4d83aqTkq6TGvXts",
"wallpapers": {
"$elemMatch": {
"role": "clone",
"_metadata.master": "vwb22W4MhkqtvAp89"
}
}
},
{
"$set": {
"wallpapers.$": {
"_id": "D33WNZh7Bg4itPdhk",
"_metadata": {
"master": "b4d83aqTkq6TGvXts",
"isMaster": false
},
"role": "clone"
}
}
}
)
So I would like to have the element in the wallpapers array replaced. However, the result I get is:
{
"_id" : "XqEQYpitGFG3nnf3C",
"wallpapers" : [
{
"_metadata" : {
"master" : "vwb22W4MhkqtvAp89",
"isMaster" : false
},
"role" : "master",
"_id" : ""
},
{
"_metadata" : {
"master" : "vwb22W4MhkqtvAp89",
"isMaster" : false
},
"role" : "clone",
"_id" : ""
},
{
"_id" : "D33WNZh7Bg4itPdhk",
"_metadata" : {
"master" : "b4d83aqTkq6TGvXts",
"isMaster" : false
},
"role" : "clone"
}
],
"ancestors" : [
"vwb22W4MhkqtvAp89",
"tqzqfum9uMs47xcHW",
"b4d83aqTkq6TGvXts",
"XqEQYpitGFG3nnf3C"
]
}
So it replaces the wrong element.
It seems that the position .$ refers to is the one from the selector of the ancestors field.
Is this a bug or a limitation? Is there a solution (e.g. anything like .$1 and .$2 ?
I'm using MongoDB 3.2.6.

In your update operation query, use the dot notation as:
db.getCollection('locations').update(
{
"ancestors": "b4d83aqTkq6TGvXts",
"wallpapers.role": "clone", // <--- dot notation
"wallpapers._metadata.master": "vwb22W4MhkqtvAp89" // <-- dot notation
},
{
"$set": {
"wallpapers.$": {
"_id": "D33WNZh7Bg4itPdhk",
"_metadata": {
"master": "b4d83aqTkq6TGvXts",
"isMaster": false
},
"role": "clone"
}
}
}
)

Related

Get filtered elements from array of object in mongodb document based on flag in elements

I have a one collection called User. Every user consists data like below document.
I want to get an user with history data but history array should contains only active records in the array.
{
"_id" : ObjectId("62f1df89fd621s2c419e5d47"),
"name" : "Test User",
"createDate" : ISODate("2022-08-25T04:43:33.949Z"),
"history" : [
{
"departmentName" : "department1",
"active" : false
},
{
"departmentName" : "department2",
"active" : true
},
{
"departmentName" : "department3",
"active" : false
}
],
"updateDate" : ISODate("2022-08-25T05:26:53.281Z")
}
This is the output I want:
{
"_id" : ObjectId("62f1df89fd621s2c419e5d47"),
"name" : "Test User",
"createDate" : ISODate("2022-08-25T04:43:33.949Z"),
"history" : [
{
"departmentName" : "department2",
"active" : true
}
],
"updateDate" : ISODate("2022-08-25T05:26:53.281Z")
}
Tried with the below query but unable to get the expected result
db.getCollection('users')
.aggregate([{
$match : {'name' : 'Test User','history.active' : true}
}])
You just need to filter the histroy array - using $filter, like so:
db.collection.aggregate([
{
$match: {
"name": "Test User",
"history.active": true
}
},
{
$addFields: {
history: {
$filter: {
input: "$history",
cond: {
$eq: [
"$$this.active",
true
]
}
}
}
}
}
])
Mongo Playground

Update value of key in Object in nested array of objects in MongoDB

I am trying to update data of "array1.array2._id": ObjectId("627a6fab60dc3c523b396af1") and Set Name to John But it's updating in all array2's first element's name to John.
db.getCollection('tests')
.updateOne({ "array1.array2._id": ObjectId("627a6fab60dc3c523b396af1") },{ $set: { "array1.$[].array2.$.name" : "John" } })
{
"_id" : ObjectId("627a6fab60dc3c523b396aec"),
"array1" : [
{
"array2" : [
{
"_id" : ObjectId("627a6fab60dc3c523b396af1"),
"name" : "test"
},
{
"_id" : ObjectId("627a6fab60dc3c523b396af2"),
"name" : "ABC"
}
],
"_id" : ObjectId("627a6fab60dc3c523b396aed")
},
{
"array2" : [
{
"_id" : ObjectId("627a6fab60dc3c523b396af3"),
"name" : "XYZ"
},
{
"_id" : ObjectId("627a6fab60dc3c523b396af4"),
"name" : "Testing"
}
],
"_id" : ObjectId("627a6fab60dc3c523b396aee")
}
]
}
Based on this great answer by #R2D2, you can do:
db.collection.update({
"array1.array2._id": ObjectId("627a6fab60dc3c523b396af1")
},
{
$set: {
"array1.$[].array2.$[y].name": "John"
}
},
{
arrayFilters: [
{
"y._id": ObjectId("627a6fab60dc3c523b396af1")
}
]
})
As you can see on this playground example

Query to update an array field by using another array field of same document in mongodb

Scenario
I've the following document from Chat collection with an array of messages and members in the chat.
And for each message, there will be status field which will store the delivered and read timestamp with respect to users.
{
"_id" : ObjectId("60679797b4365465745065b2"),
"members" : [
ObjectId("604e02033f4fc07b6b82771c"),
ObjectId("6056ef4630d7b103d8043abd"),
ObjectId("6031e3dce8934f11f8c9a79c")
],
"isGroup" : true,
"createdAt" : 1617401743720.0,
"updatedAt" : 1617436504453.0,
"messages" : [
{
"createdAt" : 1617401743719.0,
"updatedAt" : 1617401743719.0,
"_id" : ObjectId("60679797b4365465745065b3"),
"body" : "This is test message",
"senderId" : ObjectId("6031e3dce8934f11f8c9a79c"),
"status" : []
}
]
}
So, I want to insert the following data, into messages.status array, to know when the message is received/read by the member.
{
receiverId: <member of chat>
deliveredAt: <timestamp>
readAt: <timestamp>
}
Question
How to write a query to insert the above json for each member (except the sender) in the status array by using the data from existing field?
So that, after query, the document should look like this:
{
"_id" : ObjectId("60679797b4365465745065b2"),
"members" : [
ObjectId("604e02033f4fc07b6b82771c"),
ObjectId("6056ef4630d7b103d8043abd"),
ObjectId("6031e3dce8934f11f8c9a79c")
],
"isGroup" : true,
"createdAt" : 1617401743720.0,
"updatedAt" : 1617436504453.0,
"messages" : [
{
"createdAt" : 1617401743719.0,
"updatedAt" : 1617401743719.0,
"_id" : ObjectId("60679797b4365465745065b3"),
"body" : "This is test message",
"senderId" : ObjectId("6031e3dce8934f11f8c9a79c"),
"status" : [{
"receiverId": ObjectId("604e02033f4fc07b6b82771c")
"deliveredAt": <timestamp>
"readAt": <timestamp>
}, {
"receiverId": ObjectId("6056ef4630d7b103d8043abd")
"deliveredAt": <timestamp>
"readAt": <timestamp>
}]
}
]
}
Edit
I'm able to do this for static data.
Link: https://mongoplayground.net/p/LgVPfRoXL5p
For easy understanding: I've to map the members array and insert it into the status field of the messages
MongoDB Version: 4.0.5
You can use the $function operator to define custom functions to implement behavior not supported by the MongoDB Query Language. So along with updates-with-aggregate-pipeline and $function you can update messages.status array with only receiver's details as shown below:
NOTE: Works only with MongoDB version >= 4.4.
Try this:
let messageId = ObjectId("60679797b4365465745065b3");
db.chats.update(
{ "messages._id": messageId },
[
{
$set: {
"messages": {
$map: {
input: "$messages",
as: "message",
in: {
$cond: {
if: { $eq: ["$$message._id", messageId] },
then: {
$function: {
body: function (message, members) {
message.status = [];
for (let i = 0; i < members.length; i++) {
if (message.senderId.valueOf() != members[i].valueOf()) {
message.status.push({
receiverId: members[i],
deliveredAt: new Date().getTime(),
readAt: new Date().getTime()
})
}
}
return message;
},
args: ["$$message", "$members"],
lang: "js"
}
},
else: "$$message"
}
}
}
}
}
}
]
);
Output:
{
"_id" : ObjectId("60679797b4365465745065b2"),
"members" : [
ObjectId("604e02033f4fc07b6b82771c"),
ObjectId("6056ef4630d7b103d8043abd"),
ObjectId("6031e3dce8934f11f8c9a79c")
],
"isGroup" : true,
"createdAt" : 1617401743720,
"updatedAt" : 1617436504453,
"messages" : [
{
"_id" : ObjectId("60679797b4365465745065b3"),
"createdAt" : 1617401743719,
"updatedAt" : 1617401743719,
"body" : "This is test message",
"senderId" : ObjectId("6031e3dce8934f11f8c9a79c"),
"status" : [
{
"receiverId" : ObjectId("604e02033f4fc07b6b82771c"),
"deliveredAt" : 1617625735318,
"readAt" : 1617625735318
},
{
"receiverId" : ObjectId("6056ef4630d7b103d8043abd"),
"deliveredAt" : 1617625735318,
"readAt" : 1617625735318
}
]
},
{
"_id" : ObjectId("60679797b4365465745065b4"),
"createdAt" : 1617401743719,
"updatedAt" : 1617401743719,
"body" : "This is test message",
"senderId" : ObjectId("6031e3dce8934f11f8c9a79d"),
"status" : [ ]
}
]
}
Demo - https://mongoplayground.net/p/FoOvxXp6nji
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
The filtered positional operator $[] identifies the array elements that match the arrayFilters conditions for an update operation, e.g.
db.collection.update({
"messages.senderId": "6031e3dce8934f11f8c9a79c" // query
},
{
"$push": {
"messages.$[m].status": [ // push into the matching element of arrayFilters
{
"receiverId": ObjectId("604e02033f4fc07b6b82771c")
},
{
"receiverId": ObjectId("6056ef4630d7b103d8043abd")
}
]
}
},
{
arrayFilters: [
{
"m.senderId": "6031e3dce8934f11f8c9a79c" // matches array element where senderId is 6031e3dce8934f11f8c9a79c
}
]
})
Note- add index to messages.senderId for performance

How to remove a document inside an array in mongodb using $pull

I have the following document structure
{
"_id" : ObjectId("5ffef283f1f06ff8524aa2c2"),
"applicationName" : "TestApp",
"pName" : "",
"environments" : [],
"stages" : [],
"createdAt" : ISODate("2021-01-15T09:51:35.546Z"),
"workflows" : [
[
{
"pName" : "Test1",
"wName" : "TestApp_Test1",
"agent" : ""
},
{
"pName" : "Test2",
"wName" : "TestApp_Test2",
"agent" : ""
}
],
[
{
"pName" : "Test1",
"wName" : "TestApp_Test1",
"agent" : ""
}
]
],
"updatedAt" : Date(-62135596800000)
}
I wish to remove the occurrences of
{
"pName" : "Test1",
"wName" : "TestApp_Test1",
"agent" : ""
}
The resultant document should look like
{
"_id" : ObjectId("5ffef283f1f06ff8524aa2c2"),
"applicationName" : "TestApp",
"pName" : "",
"environments" : [],
"stages" : [],
"createdAt" : ISODate("2021-01-15T09:51:35.546Z"),
"workflows" : [
[
{
"pName" : "Test2",
"wName" : "TestApp_Test2",
"agent" : ""
}
]
],
"updatedAt" : Date(-62135596800000)
}
I've tried the below mongo query
db.getCollection('workflows').update({_id:ObjectId('5ffef283f1f06ff8524aa2c2')},
{$pull:{workflows: { $elemMatch: {pipelineName: 'Test1'}}}} )
This is removing all the documents from workflows field including Test2 since Test1 is matched.
How can we remove only the entries for Test1 and keep the others?
You can do it using the positional operator "$[]" :
db.getCollection('workflows').update({_id: ObjectId("5ffef283f1f06ff8524aa2c2") }, {$pull: {"workflows.$[]":{pName:"Test1" } } } )
but the schema looks abit strange and after the update you will have empty arrays inside workflows if all elements got deleted in the sub-array.
To fix the empty sub-arrays you will need to perform second operation to remove them:
db.getCollection('workflows').update({_id: ObjectId("5ffef283f1f06ff8524aa2c2") }, {$pull: {"workflows":[] } } )
You cannot use $elemMatch as it returns the first matching element in the array.
I am not sure there is another best way to do this with the provided schema design.
play
db.collection.aggregate({
"$unwind": "$workflows"
},
{
"$unwind": "$workflows"
},
{
"$match": {
"workflows.pName": {
"$ne": "Test1"
}
}
},
{
"$group": {
"_id": "$_id",
workflows: {
$push: "$workflows"
},
applicationName: {
"$first": "$applicationName"
}
}
},
{
"$group": {
"_id": "$_id",
workflows: {
$push: "$workflows"
},
applicationName: {
"$first": "$applicationName"
}
}
})
unwind twice required to de-normalize the data
match to filter out the unnecessary doc
group twice required to bring the required output
You can save this to a collection using $out as last stage.

How to update field in document sub-array in mongo

In a database with these documents
{
"_id" : ObjectId("5448f241e47010336375bb21"),
"lid" : "Ridali",
"items" : [
{
"product" : "dogfood", ,
"done" : false
}
],
}
{
"_id" : ObjectId("5448fc15e47010336375bb23"),
"lid" : "Qitula",
"items" : [
{
"product" : "measure kitchen cab",
"done" : false,
"tags" : [
"11x30"
]
},
{
"product" : "radiators",
"done" : true
},
{
"product" : "dogfood",
"done" : true
}
],
}
How would I update dogfood to catfood for lid:"Qitula" ? I have tried variations of
db.lists.update({lid: "Qitula","items: {$elemMatch: {product: "dogfood"}}},{$set: {"items.product": "catfood"}})
without success.
db.lists.update({lid: "Qitula","items.product": "dogfood" }, { $set : { "items.$.product" : "catfood" }})
Check documentation - http://docs.mongodb.org/manual/reference/operator/update/positional/#up.S
To update subdocument you need to use the positional $ operator
db.lists.update({
lid: "Qitula",
items: {$elemMatch: {product: "dogfood"}}
},
{$set: {"items.$.product": "catfood"}
})

Resources