I have a dataset like this:
{
"_id" : ObjectId("5a7bee68996b551034015a15"),
"sequenceid" : 1,
"fruit" : [
{
"name" : "#APPLE",
"value" : 2
},
{
"name" : "#BANANA",
"value" : 1
},
{
"name" : "#ORANGE",
"value" : 5
}
}
want to update only Apple value i.e from 2 to 25. Expected result will be:
{
"_id" : ObjectId("5a7bee68996b551034015a15"),
"sequenceid" : 1,
"fruit" : [
{
"name" : "#APPLE",
"value" : 25
},
{
"name" : "#BANANA",
"value" : 1
},
{
"name" : "#ORANGE",
"value" : 5
}
}
I tried the code but this will replace all entry and do only one entry. My code is
db.Collection.update({'sequenceid': 1}, {$set: {'fruit' : {'name': '#APPLE', 'value': parseFloat(25)}}}, function(error, result){
if(error){
console.log('error');
} else {
console.log('success');
}
});
It can produce the result:
{
"_id" : ObjectId("5a7bee68996b551034015a15"),
"sequenceid" : 1,
"fruit" : [
{
"name" : "#APPLE",
"value" : 25
}
}//Delete all my rest entry
How I can Do this. I am a newbie on MongoDB
This will update only the first occurrence of record.For reference MongoDB - Update objects in a document's array (nested updating)
db.collection.update({ _id: ObjectId("5a7bf5586262dc7b9f3a8422") ,"fruit.name" : "#APPLE"},
{ $set:
{
"fruit.$.value" : 25
}
})
If you are writing JavaScript query then you can update like this
db.collection.find({'sequenceid': 1}).forEach(function(x){
x.fruit.forEach(function(y){
if(y.name=="#APPLE")
{
y.value = 25
}
})
db.collection.update({_id:x._id},x)
})
db.Collection.update({
_id: ObjectId("5a7bee68996b551034015a15"),
"fruit": {
$elemMatch: {
"name": "#APPLE"
}
}
}, {
$set: {
"fruit.$.value": 25
}
})
In above update operation $elemMatch operator is used to search a value in an array and in $set stage positional operator $ is used to update value of specific key belonging to an array element
Related
I need to update a particular element of the nested array in mongoDB
My mongoDB data looks like below. I need to match the value accessid and name to update the status. The input content has
{"accessid" : 1627047023995, "name" : Name 09, "status" : 100 }
The input content may belong to any level
{
"_id" : ObjectId("60fac46ffcbf5287248460a9"),
"levelone" : [
{
"level" : [
{
"name" : "Name 01",
"status" : 5
},
{
"name" : "Name 02",
"status" : 0
},
{
"name" : "Name 03",
"status" : 0
}
],
"accessid" : "1627047023995"
},
{
"level" : [
{
"name" : "Name 09",
"status" : 5
},
{
"name" : "Name 15",
"status" : 3
}
],
"accessid" : "1627047023995"
}
],
"createdAt" : ISODate("2021-07-23T13:30:23.995Z")
}
I have tried to update the status, but it is updating only the first index value - name: Name 01 status. Please guide to resolve the issue.
collections.updateOne({
'levelone.level.accessid': accessid,
'levelone.level.name': name
}, { '$set': { 'levelone.$.level.status': status } }).exec();
you can use arrayFilters positional update,
query with $elemMatch to filter the main document
arrayFilters to define a variable for accessid and b for name
await collections.updateOne({
levelone: {
$elemMatch: {
accessid: accessid,
"level.name": name
}
}
},
{
$set: {
"levelone.$[a].level.$[b].status": status
}
},
{
arrayFilters: [
{ "a.accessid": accessid },
{ "b.name": name }
]
})
Playground
I want to update Itinirary which is embedded subdocument inside the
packages which itself is a embedded document.I tried using index and
was successful like this :
"$set":{'packages.$.itinerary.0.to': "kausaltar"}
but I don't want to use index like 0,1 in itinerary update.Please can you help me.
My JSON schema is like this :
{
"_id" : ObjectId("5e1ca76b9f96d17c449de177"),
"org_id" : "22222222222",
"packages" : [
{
"_id" : ObjectId("5e1ca76b9f96d17c449de17a"),
"region" : "ppopopop",
"itinerary" : [
{
"_id" : ObjectId("5e1ca76b9f96d17c449de17d"),
"id" : 1,
"from" : "ppopopop",
"to" : "ashinnkn",
"mode" : "4444444444",
"day" : 2,
"duration_hrs" : 3
},
{
"_id" : ObjectId("5e1ca76b9f96d17c449de17c"),
"id" : 2,
"from" : "44444444444",
"to" : "Faketon2",
"mode" : "4444444444",
"day" : 2,
"duration_hrs" : 3
},
{
"_id" : ObjectId("5e1ca76b9f96d17c449de17b"),
"id" : 3,
"from" : "55555555555",
"to" : "ashin",
"mode" : "55555555",
"day" : 2,
"duration_hrs" : 3
}
],
"image_url" : "sadfasfsa",
},
{
"_id" : ObjectId("5e1ca76b9f96d17c449de178"),
"region" : "bktll",
"itinerary" : [
{
"_id" : ObjectId("5e1ca76b9f96d17c449de179"),
"id" : 1,
"from" : "mmkkkkm",
"to" : "ashin",
"mode" : "SkkkkA",
"day" : 2,
"duration_hrs" : 3
}
],
"image_url" : "sadfasfsa",
}
]
}
}
I want to update itinerary field inside packages which itself is an embedded document.
And my code is like this :
AgentPackage.update({
"_id" : mongoose.Types.ObjectId("5e1ca76b9f96d17c449de177"),
"packages.region" : "ppopopop",
'packages.itinerary.id': 2,
}, {$set: {'packages.itinerary.$$.from': "test" }}
I am not being able to update.I don't want to use indexing like 0,1 INSIDE query.
Try this :
If you've only one object inside packages with region : "ppopopop", then try this (this should suffice in most cases as you might not have duplicate regions with same name) :
AgentPackage.update({
_id: ObjectId("5e1ca76b9f96d17c449de177"), "packages.region": "ppopopop"
}, { $set: { "packages.$.itinerary.$[item].to": 'kausaltar' } }, {
arrayFilters: [{ 'item.id': 2 }]
})
If you've got multiple objects inside packages with region : "ppopopop", then try this :
AgentPackage.update({
_id: ObjectId("5e1ca76b9f96d17c449de177"), "packages.region": "ppopopop" // Here this "packages.region": "ppopopop" is optional as _id will only bring one document else might be helpful to bring only docs with region: ppopopop right after filter.
}, { $set: { "packages.$[eachPackage].itinerary.$[eachItinerary].to": 'kausaltar' } }, {
arrayFilters: [{ 'eachPackage.region': "ppopopop" }, { 'eachItinerary.id': 2 }]
})
Ref : update-positional-filtered
You can do it with $arrayfilter
db.getCollection("unit").update({_id: ObjectId("5e1ca76b9f96d17c449de177")}, { $set: { "packages.$[t].itinerary.$[d].from": "test" } },
{ arrayFilters: [ { "t.region": "ppopopop" }, {"d.id":15}]})
I'm trying to remove an entry from an array which nested in another array as you can see below:
{
"_id" : ObjectId("548f5ca9fa9dc1000016a725"),
"entries" : [
{
"_id" : ObjectId("548f5cc8fa9dc1000016a726"),
"content" : [
{
"order" : ObjectId("5489fa9127f1310000bea2ed"),
"order_id" : "305429245",
"item_id" : "305429245-1"
},
{
"order" : ObjectId("5489fa9127f1310000bea2ce"),
"order_id" : "330052901",
"item_id" : "330052901-1"
}
],
"stop_number" : 1
},
{
"stop_number" : 2,
"expected_arrival" : ISODate("2014-12-15T17:11:11.000Z"),
"expected_departure" : ISODate("2014-12-15T19:03:17.000Z"),
"_id" : ObjectId("548fb2826e52c20000bd2299"),
"content" : []
}
]
}
And i'm trying to remove the entry that have '305429245-1', so i used:
Q.npost(Manifests, 'findOneAndUpdate', [
{ '_id': id },
{
'$pull': {
'entries.content': { item_id: line_item_id }
}
}
])
where 'id' is the ObjectID (548f5ca9fa9dc1000016a725) and line_item_id = 305429245-1, however, this doesn't work. Can anyone let me know what am i doing wrong?
Try to use find and Update functions separately instead of findOneAndUpdate
Model.find({'_id: id'},function(err,callback){...})
{
//handle callback
}
Model.update({'_id: id'}, {$pull: {'entries.content': item_id: line_item_id}}, function(err,callback){..} )
{
//do some logic or handle callback
}
here Model which i mentioned,should be the model you are using.
I want to update nested array in Mongo DB (using Node.js). I am able to get the array index location.
How can I update same ? I am facing some problem while using escape character in $set
Here is what I am doing :
testCollection.update({
"uniqueID": someID,
"topLevelObject.innerObjectValue": innerObjectVal
}, {
$set: {
'array.' + outerArrayIndex + '.value': updatedValue,
}
}, function(err, result) {
if (err) {
console.log("Error occurred while updating db info");
}
}
);
It's hard to tell what the problem is because you have not included an example document or shown an error message or what goes wrong. Assuming your document looks like
{
"_id" : 0,
"array" : [{ "value" : 2 }, { "value" : 6 }]
}
then your above query should work, e.g.
db.test.update({ "_id" : 0 }, { "$set" : { "array.1.value" : 906 } })
will modify the document to
{
"_id" : 0,
"array" : [{ "value" : 2 }, { "value" : 906 }]
}
I omitted the other query condition because it isn't necessary with a unique id specified - perhaps the condition isn't matching any documents?
If you document looks like
{
"_id" : 0,
"array" : [2, 6]
}
then you don't need the .value in the update query:
db.test.update({ "_id" : 0 }, { "$set" : { "array.1" : 906 } })
I'd also check that the string concatenation with the variable outerArrayIndex is producing the correct field path.
In a mongo (2.4.x) collection with documents with this structure:
db.col.insert({ "_id" : { "owner" : "john" }, "value" : 10 });
db.col.insert({ "_id" : { "owner" : "mary" }, "value" : 20 });
I am using mongoose (3.5.4) and trying to run an aggregation pipeline without success. This works fine from the mongo command line client:
> db.col.aggregate({ $match : { "_id.owner": "john" } });
{ "result" : [ { "_id" : { "owner" : "john" }, "value" : 10 } ], "ok" : 1 }
But it does not work as expected when I use mongoose:
Col.aggregate(
{ $match : { "_id.owner": "john" } },
function(err, result) {
console.log("ERR : " + err + " RES : " + JSON.stringify(result));
}
);
ERR : null RES : []
This is the mongoose Schema I am using:
var Col = new Schema({
_id: {
owner: String
},
value: Number
});
I have to say that a simple Col.find({ "_id.owner": "john" }) works as expected.
How could I make it work? I can not modify the structure of my documents.
As I workaround I included a $project before the match, but I am still looking for a cleaner solution:
{
$project: {
"_id": 0,
"owner": "$_id.owner",
"value": 1
}
}