How to update nested array document in mongodb - arrays

I have a collection looks like
{
"Aid":12234,
"items":{
"itemId":"SP897474",
"Blocks":[
{
"blockId":"W23456",
"name":"B1",
"innerBlock":[
{
"id":"S23490",
"name":"IB1",
"state":true
},
{
"id":"S23491",
"name":"IB2",
"state":true
},
{
"id":"S23492",
"name":"IB3",
"state":true
}
],
"active":true
},
{
"blockId":"W23457",
"name":"B2",
"innerBlock":[
{
"id":"S23482",
"name":"IB1",
"state":true
},
{
"id":"S23483",
"name":"IB2",
"state":true
}
],
"active":false
}
]
},
"active":true
}
I'm not able to update fields that is of innerBlock array, specially name, status because of nesting. Basically, I wanted to update mentioned fields .Iam already try this query
User.update({
"items.Blocks.innerBlock.id": req.body.id,
"Aid": req.body.Aid
}, {
"$set": {
"items.Blocks.$.InnerBlock.$.name": req.body.name
}
})
It shows an error given below
"errmsg": "Too many positional (i.e. '$') elements found in path 'items.Blocks.$.InnerBlock.$.name'"
I'm not sure how to fix it.What can be the query in mongo shell? Thanks.

Only one positional operator available right now with mongoDB. There are opened feature request for that https://jira.mongodb.org/browse/SERVER-831
check the answer https://stackoverflow.com/a/14855633/2066271

Related

Mongodb Updating Nested Arrays

I am trying to update the ordered quantity of the first article of the first order.
Insert and update instructions:
db.client.insertOne({
"noClient":1, "nomClient":"John Doe", "noTéléphone":"1234567890",
"commandes":[
{
"noCommande":1, "dateCommande":"22-11-2022",
"lignesCommande":[
{ "article":{"noArticle":1, "description":"Lenovo ThinkPad", "prixUnitaire":12000000, "quantiteEnStock":250}, "quantite":13 },
{ "article":{"noArticle":2, "description":"Iphone14", "prixUnitaire":16000000, "quantiteEnStock":123}, "quantite":2 },
{ "article":{"noArticle":3, "description":"All star shoes", "prixUnitaire":12500, "quantiteEnStock":15}, "quantite":1 },
{ "article":{"noArticle":4, "description":"Cahier 200pages", "prixUnitaire":12000, "quantiteEnStock":27}, "quantite":2 }
]
},
{
"noCommande":2, "dateCommande":"23-11-2022",
"lignesCommande":[
{ "article":{"noArticle":5, "description":"Airpods", "prixUnitaire":1300000, "quantiteEnStock":13}, "quantite":1 },
{ "article":{"noArticle":4, "description":"Cahier 200pages", "prixUnitaire":12000, "quantiteEnStock":23}, "quantite":1 }
]
}
]
});
db.client.updateOne({"commandes.noCommande":1, "commandes.lignesCommande.article.noArticle" :1},
{"$set" : {"commandes.lignesCommande.$.quantite":1}})
Screenshot of code:
Following command doesn't work:
db.client.updateOne({"commandes.noCommande":1, "commandes.lignesCommande.article.noArticle" :1},
{"$set" : {"commandes.lignesCommande.$.quantite":1}})
This is actually a pain. Mongodb does not allow multiple positional operators (meaning you cannot use $ directly within your query). Instead, you could use positional filters with arrayFilters.
Playground example - https://mongoplayground.net/p/tDGYeNIYco4
db.collection.update({
"commandes.noCommande": 1
},
{
$set: {
"commandes.$.lignesCommande.$[lig].quantite": 100
}
},
{
arrayFilters: [
{
"lig.article.noArticle": 1
}
]
})

How to write a MongoDB query to perform the following update?

I want to update the inner fields of specific questions for a specific exam such as user_answer, isAnswered, etc in the Mongo document below.
Document File for the above image :
{
"_id":{"$oid":"60508fb1c4b07a4134e75644"},
"student_id":"5faaac5d35b7ba4ed406e765",
"exams":[
{"score":null,
"time_taken":null,
"exam_taken":true,
"_id":{"$oid":"60508fb1c4b07a4134e75645"},
"exam_id":"5fbfc8ea9831540072063e62",
"questions":[
{"user_answer":null,
"isAnswered":false,
"isUnanswered":true,
"isFlagged":false,
"_id":{"$oid":"5fbfc8659831540072063e61"}
}
]
}
]
}
I wrote a query for the same but it doesn't work.
try{
await req.db
.collection('result')
.findOneAndUpdate({ student_id: ObjectId("5faaac5d35b7ba4ed406e765"), "exams._id": ObjectId(exam_id),"exams.questions._id":ObjectId(question_id) }, {
$set: {
'questions.$.user_answer': answer,
'questions.$.isAnswered':true,
'questions.$.isUnanswered':false,
'questions.$.isFlagged':false
}
}
);
res.status(201).end();
}catch(e){
console.log(e);
}
Though I am sure there is something wrong with the query itself, I'll highly appreciate it if anyone of you people can tell me how to perform such type of update.
Thank you for the same
Since MongoDB 3.5.12, you can use the update operator with the option arrayFilters to updated nested array elements.
db.collection.update({
"student_id": ObjectId("5faaac5d35b7ba4ed406e765"),
"exams.exam_id": ObjectId("5fbfc8ea9831540072063e62")
},
{
$set: {
"exams.$.questions.$[question].user_answer": "You are the best",
"exams.$.questions.$[question].isAnswered": true,
"exams.$.questions.$[question].isUnanswered": false,
"exams.$.questions.$[question].isFlagged": false
}
},
{
arrayFilters: [
{
"question._id": ObjectId("5fbfc8659831540072063e61")
}
],
multi: true
})

Mongoose FindOne - only return fields which match condition

I am trying to query my collection of matches (games) and find if a certain user has already sent data to the 'reportMessages' array of Objects.
const results = await Match.findOne({ 'users': req.params.userIdOfReportSender, '_id': req.params.matchId, 'reportMessages.sentBy': req.params.userIdOfReportSender }, 'reportMessages' )
However, the above query returns the following:
{
_id: 5fd382c65d5395e0778f2f8a,
reportMessages: [
{
_id: 5fd610f27ae587189c45b6ca,
content: 'jajatest',
timeStamp: 2020-12-13T13:02:42.102Z,
sentBy: 'XbVvm6g3nsRmPg3P1pBvVl84h6C2'
},
{ sentBy: "'anotheruser123" }
]
}
How can I get it to only return the first reportMessage, i.e. the one sent by XbVvm6g3nsRmPg3P1pBvVl84h6C2?
Mongoose findOne docs (https://mongoosejs.com/docs/api.html#model_Model.findOne) show that you can provide arguments to say which fields to select (in their case 'name length' but don't show a way to only select the fields in case they match a certain condition.
Is this even possible? Tried googling this seemingly easy question for quite some time without success
Kind regards
You can get only the subdocument you want with this aggregation query:
Match.aggregate([
{
$match: { _id: req.params.matchId }
},
{
$project: {
reportMessages: {
$filter: {
input: '$reportMessages',
as: 'msg',
cond: { $eq: ['$$msg.sentBy', req.params.userIdOfReportSender] }
}
}
}
},
{
$project: {
reportMessage: { $arrayElemAt: [ '$reportMessages', 0 ] },
}
},
{ $replaceWith: '$reportMessage' }
]);
Note that you only need to specify the document _id to get a single result, since _ids are unique.

How to insert array/list of objects in existing MongoDB document?

I have a mongo collection where docs have been already stored. The structure is of a single doc is something like this:
"_id":ObjectId("55c3043ab165fa6355ec5c9b"),
"address":{
"building":"522",
"coord":[
-73.95171,
40.767461
],
"street":"East 74 Street",
"zipcode":"10021"
}
}
Now I want to update the doc by inserting a new field "persons" with value being a list of objects [{"name":"marcus", "contact":"420"}, {"name":"modiji", "contact":"111"}], so after insertion the above doc should look like this:
"_id":ObjectId("55c3043ab165fa6355ec5c9b"),
"address":{
"building":"522",
"coord":[
-73.95171,
40.767461
],
"street":"East 74 Street",
"zipcode":"10021"
},
"persons":[
{
"name":"marcus",
"contact":"420"
},
{
"name":"modiji",
"contact":"111"
}
]
}
Can anyone please help me with then correct $set syntax? Also, it would be really helpful if anyone can suggest an efficient way to update a key's value, which is a list of objects so that I can push some new objects inside the existing list.
You can use the updateOne command along with $set operator to achieve it.
db.<Collection-Name>.updateOne({
"_id":ObjectId("55c3043ab165fa6355ec5c9b")
}, {
"$set": {
"persons":[
{
"name":"marcus",
"contact":"420"
},
{
"name":"modiji",
"contact":"111"
}
]
}
})
If you want to push additional data into the array, you can use the below command.
db.<Collection-Name>.updateOne({
"_id":ObjectId("55c3043ab165fa6355ec5c9b")
}, {
"$push": {
"persons": {
"name":"sample",
"contact":"1234"
}
}
})
To push multiple arrays of objects in a single command, use the below query
db.<Collection-Name>.updateOne({
"_id":ObjectId("55c3043ab165fa6355ec5c9b")
}, {
"$push": {
"persons": {
"$each": [
{
"name":"sample1",
"contact":"5678"
},
{
"name":"sample2",
"contact":"90123"
}
]
}
}
})

MongoDB rename database field within array

I need to rename indentifier in this:
{ "general" :
{ "files" :
{ "file" :
[
{ "version" :
{ "software_program" : "MonkeyPlus",
"indentifier" : "6.0.0"
}
}
]
}
}
}
I've tried
db.nrel.component.update(
{},
{ $rename: {
"general.files.file.$.version.indentifier" : "general.files.file.$.version.identifier"
} },
false, true
)
but it returns: $rename source may not be dynamic array.
For what it's worth, while it sounds awful to have to do, the solution is actually pretty easy. This of course depends on how many records you have. But here's my example:
db.Setting.find({ 'Value.Tiers.0.AssetsUnderManagement': { $exists: 1 } }).snapshot().forEach(function(item)
{
for(i = 0; i != item.Value.Tiers.length; ++i)
{
item.Value.Tiers[i].Aum = item.Value.Tiers[i].AssetsUnderManagement;
delete item.Value.Tiers[i].AssetsUnderManagement;
}
db.Setting.update({_id: item._id}, item);
});
I iterate over my collection where the array is found and the "wrong" name is found. I then iterate over the sub collection, set the new value, delete the old, and update the whole document. It was relatively painless. Granted I only have a few tens of thousands of rows to search through, of which only a few dozen meet the criteria.
Still, I hope this answer helps someone!
Edit: Added snapshot() to the query. See why in the comments.
You must apply snapshot() to the cursor before retrieving any documents from the database.
You can only use snapshot() with unsharded collections.
From MongoDB 3.4, snapshot() function was removed. So if using Mongo 3.4+ ,the example above should remove snapshot() function.
As mentioned in the documentation there is no way to directly rename fields within arrays with a single command. Your only option is to iterate over your collection documents, read them and update each with $unset old/$set new operations.
I had a similar problem. In my situation I found the following was much easier:
I exported the collection to json:
mongoexport --db mydb --collection modules --out modules.json
I did a find and replace on the json using my favoured text editing utility.
I reimported the edited file, dropping the old collection along the way:
mongoimport --db mydb --collection modules --drop --file modules.json
Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update of a field based on its own value:
// { general: { files: { file: [
// { version: { software_program: "MonkeyPlus", indentifier: "6.0.0" } }
// ] } } }
db.collection.updateMany(
{},
[{ $set: { "general.files.file": {
$map: {
input: "$general.files.file",
as: "file",
in: {
version: {
software_program: "$$file.version.software_program",
identifier: "$$file.version.indentifier" // fixing the typo here
}
}
}
}}}]
)
// { general: { files: { file: [
// { version: { software_program: "MonkeyPlus", identifier: "6.0.0" } }
// ] } } }
Literally, this updates documents by (re)$setting the "general.files.file" array by $mapping its "file" elements in a "version" object containing the same "software_program" field and the renamed "identifier" field which contains what used to be the value of "indentifier".
A couple additional details:
The first part {} is the match query, filtering which documents to update (in this case all documents).
The second part [{ $set: { "general.files.file": { ... }}}] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline):
$set is a new aggregation operator which in this case replaces the value of the "general.files.file" array.
Using a $map operation, we replace all elements from the "general.files.file" array by basically the same elements, but with an "identifier" field rather than "indentifier":
input is the array to map.
as is the variable name given to looped elements
in is the actual transformation applied on elements. In this case, it replaces elements by a "version" object composed by a "software_program" and a "identifier" fields. These fields are populated by extracting their previous values using the $$file.xxxx notation (where file is the name given to elements from the as part).
I had to face the issue with the same schema. So this query will helpful for someone who wants to rename the field in an embedded array.
db.getCollection("sampledocument").updateMany({}, [
{
$set: {
"general.files.file": {
$map: {
input: "$general.files.file",
in: {
version: {
$mergeObjects: [
"$$this.version",
{ identifer: "$$this.version.indentifier" },
],
},
},
},
},
},
},
{ $unset: "general.files.file.version.indentifier" },
]);
Another Solution
I also would like rename a property in array: and I used thaht
db.getCollection('YourCollectionName').find({}).snapshot().forEach(function(a){
a.Array1.forEach(function(b){
b.Array2.forEach(function(c){
c.NewPropertyName = c.OldPropertyName;
delete c["OldPropertyName"];
});
});
db.getCollection('YourCollectionName').save(a)
});
The easiest and shortest solution using aggregate (Mongo 4.0+).
db.myCollection.aggregate([
{
$addFields: {
"myArray.newField": {$arrayElemAt: ["$myArray.oldField", 0] }
}
},
{$project: { "myArray.oldField": false}},
{$out: {db: "myDb", coll: "myCollection"}}
])
The problem using forEach loop as mention above is the very bad performance when the collection is huge.
My proposal would be this one:
db.nrel.component.aggregate([
{ $unwind: "$general.files.file" },
{
$set: {
"general.files.file.version.identifier": {
$ifNull: ["$general.files.file.version.indentifier", "$general.files.file.version.identifier"]
}
}
},
{ $unset: "general.files.file.version.indentifier" },
{ $set: { "general.files.file": ["$general.files.file"] } },
{ $out: "nrel.component" } // carefully - it replaces entire collection.
])
However, this works only when array general.files.file has a single document only. Most likely this will not always be the case, then you can use this one:
db.nrel.componen.aggregate([
{ $unwind: "$general.files.file" },
{
$set: {
"general.files.file.version.identifier": {
$ifNull: ["$general.files.file.version.indentifier", "$general.files.file.version.identifier"]
}
}
},
{ $unset: "general.files.file.version.indentifier" },
{ $group: { _id: "$_id", general_new: { $addToSet: "$general.files.file" } } },
{ $set: { "general.files.file": "$general_new" } },
{ $unset: "general_new" },
{ $out: "nrel.component" } // carefully - it replaces entire collection.
])

Resources