How to update field in document sub-array in mongo - arrays

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"}
})

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

Push to array based on other attributes

Object structure (example only, there are thousands of callbacks in one object):
{
"_id" : ObjectId("5ce82dd1eed5a17f33ec025a"),
"id" : "AAA",
"pac" : "",
"callbacks" : [
{
"_id" : ObjectId("5ce82e29eed5a17f33ec0287"),
"timestamp" : 1558720040,
"type" : "data_bidir",
"seqNumber" : 49,
"messages" : [
{
"isCode" : true,
"_id" : ObjectId("5ce82e29eed5a17f33ec0294"),
"key" : "action",
"value" : "extra_long_press"
},
{
"isCode" : false,
"_id" : ObjectId("5ce82e29eed5a17f33ec0293"),
"key" : "version",
"value" : "6"
},
{
"isCode" : false,
"_id" : ObjectId("5ce82e29eed5a17f33ec0292"),
"key" : "firmware",
"value" : "0.45"
}
],
"created" : ISODate("2019-05-24T17:47:21.476Z")
},
{
"_id" : ObjectId("5ce82e42eed5a17f33ec0295"),
"timestamp" : 1558720040,
"type" : "service_geoloc",
"seqNumber" : 49,
"messages" : [
{
"isCode" : true,
"_id" : ObjectId("5ce82e42eed5a17f33ec029b"),
"key" : "lqi",
"value" : "Good"
},
{
"isCode" : false,
"_id" : ObjectId("5ce82e42eed5a17f33ec029a"),
"key" : "latitude",
"value" : "50.67593721530616"
},
{
"isCode" : false,
"_id" : ObjectId("5ce82e42eed5a17f33ec0299"),
"key" : "longitude",
"value" : "14.03118116624828"
},
{
"isCode" : false,
"_id" : ObjectId("5ce82e42eed5a17f33ec0298"),
"key" : "radius",
"value" : "8514"
},
{
"isCode" : true,
"_id" : ObjectId("5ce82e42eed5a17f33ec0297"),
"key" : "da_source",
"value" : "2"
},
{
"isCode" : true,
"_id" : ObjectId("5ce82e42eed5a17f33ec0296"),
"key" : "da_status",
"value" : "1"
}
],
"created" : ISODate("2019-05-24T17:47:46.547Z")
}
]
}
I need to push object to all messages only if a) callbacks.type is "service_geoloc" and b) if messages contains key = da_source and value = 2 (in sample data - the second callback would be affected).
The condition a) is easily managed by arrayFilters:
db.getCollection("devices").updateMany(
{ id: 'AAA'},
{ $push: {
"callbacks.$[c].messages" : {
$each: [{key: "action", value: "atlas_position_network", isCode: true}],
$position: 0
}
}
},
{ arrayFilters: [{"c.type": "service_geoloc"}], multi: true}
)
But I cannot figure out how to apply the condition b). I also tried elemMatch - it worked with both conditions but it updated only one message.
I was able to do it in 2 steps. Maybe it is impossible to do it in one step using shell.
Step 1 = push the item into messages array with general value:
db.getCollection("devices").updateMany(
{ id: 'AAA'},
{ $push: {
"callbacks.$[c].messages" : {
$each: [{key: "action", value: "atlas_position_network", isCode: true}],
$position: 0
}
}
},
{ arrayFilters: [{"c.type": "service_geoloc"}], multi: true}
)
Step 2 = Update the value based on other item on fixed position:
db.getCollection('devices').updateMany(
{ id: 'AAA' },
{ $set: { "callbacks.$[c].messages.0.value": "atlas_position_wifi"} },
{ arrayFilters: [{ "c.type": "service_geoloc", "c.messages.5.value": "6", "c.messages.5.key": "da_source" }], multi: true }
)

MongoDB update $ update operator with multiple array selector

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"
}
}
}
)

Resources