MongoDB : Add field in each array elements [duplicate] - mongodb

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 5 years ago.
I'm starting with mongoDB and I want to update a nested array in my documents to add some initial value, but I can't find a way to do it with mong.
here is my document :
{
"_id":"cTZDL7WThChSvsvBT",
"name":"abc",
"players":[
{
"playerName":"Name1"
},
{
"playerName":"Name2"
}
]
}
What I want to do :
{
"_id":"cTZDL7WThChSvsvBT",
"name":"abc",
"players":[
{
"playerName":"Name1",
"NewField1":0,
"NewField2":0
},
{
"playerName":"Name2",
"NewField1":0,
"NewField2":0
}
]
}
Does anyone have a solution for this kind of situation?

This adds the new fields to the player array ...
db.collection.update({_id: 'cTZDL7WThChSvsvBT', players: {$exists: true}}, {$set: {'players.$.NewFieldOne': 0, 'players.$.NewFieldTwo': 0}})
... but since Mongo will only update the first element of an array which matches the query you are a bit stuffed. You can, of course, choose which array element to update by using the positional operator (as in my example) or by choosing a specific element (as the previous poster suggested) but until Mongo supports 'array updates' on all elements I think you're left with a solution such as: find the relevant documents and then update each one (i.e. a client side update solution).

I finally found a way by editing directly the document in JS like this :
db.doc.find({_id: myDocId}).forEach(function (channel) {
channel.players.forEach(function (player) {
player.newField1 = 0;
player.newField2 = 0;
});
db.doc.update({_id: myDocId}, channel);
});

considering you want to update an element which is an object also,
how about this?
db.collections.updateOne({_id: "cTZDL7WThChSvsvBT"}, {$set: {"players.0.NewField1": 0, "players.0.NewField2: 0}});

Related

Robo3T delete one element inside a key in a document? [duplicate]

This question already has answers here:
How to remove array element in mongodb?
(6 answers)
Closed 2 years ago.
I have been searching all day to figure out how to do a simple delete for one element inside a document that is inside a collection. I am fairly new to mongo scripts so bear with me.
I am currently using this script to see a certain document:
db.getCollection('roles').deleteOne({"_id": "e9b4afad-cb5c-4588-9560-161867faa5b7"})
This is what the document shows in Robo3T after the it is executed:
{
"_id" : "e9b4afad-cb5c-4588-9560-161867faa5b7",
"appIds" : [
"rpt",
"wc",
"bw"
],
}
I am simply wanting to remove "rpt" from appIds. I have tried this so far and it doesn't work:
db.getCollection('roles').find({"_id": "e9b4afad-cb5c-4588-9560-161867faa5b7"}).remove({"appIds": "rpt"})
Any documentation that'll point me in the right direction?
Thanks!
It is not an easy task but I believe $pull will do the work.
The $pull operator removes from an existing array (in a doc) all instances of a value or values that match a specified condition.
I would try,
db.roles.update(
{ },
{ $pull: { appIds: "rpt"}},
{ multi: true }
)
Let me know if it works...
If you want to update a specific id just add it in the first part {}, -> {_id: *****},
See the great documentation of MongoDB at https://docs.mongodb.com/manual/reference/operator/update/pull/

Search Specific Element In array mongodb [duplicate]

This question already has answers here:
How to filter array in subdocument with MongoDB [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to find a specific object from array of objects in mongodb.
I am trying this
Company.findOne ({
"configuration.macAddress": "AB-90-dF-8d"
});
It returns me the exact company but it returns all the configuration array
I want only configuration with matching macAddress
Instead use aggregate(). $unwind the configuration array first, then you can $match the specific element only.
Company.aggregate([
{
"$unwind": "$configuration"
},
{
"$match":{
"configuration.macAddress": "AB-90-dF-8d"
}
}
]);
you can use $elemMatch to find a particular object in an array.
Company.find({ configuration: { $elemMatch: { macAddress: "AB-90-dF-8d"} } } );
can you show me your array of objects?

MongoDb: add element to array if not exists [duplicate]

This question already has answers here:
Can you specify a key for $addToSet in Mongo?
(2 answers)
Closed 6 years ago.
I'm using node.js and Mongo.db (I'm newly on Mongo). I have a document like this:
Tag : {
name: string,
videoIDs: array
}
The idea is, the server receives a JSON like
JSON: {
name: "sport",
videoId: "34f54e34c"
}
with this JSON, it has to find the tag with the same name and check if in the array it has the videoId, if not, insert it to the array.
How can I check the array and append data?
You can use $addToSet operator to check exist before append element into array.
db.tags.update(
{name: 'sport'},
{$addToSet: { videoIDs: "34f54e34c" } }
);
In this update statement example, mongoDB will find the TAG document which matches name == sport, and then check whether the videoIDs array contains 34f54e34c. If not, append it to the array.
Detail usage of $addToSet please read here.
I didn't test it, but you can try something like:
yourDb.find({ name: "sport",
videoIDs: { $in: ["34f54e34c"] } })
.update({$addToSet: { videoIDs: "34f54e34c" }});
If you need how: MongoDb in nodeJs implementation, you can start with:
http://jsfiddle.net/1ku0z1a1/
$addToSet operator check for the empty or existing array in document.
db.col_name.update({name :"name_for_match"},{$addToSet : { videoId : "video_id_value"}})

MongoDB - is there a way to $inc ALL elements in an array with one command? [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 4 years ago.
If I have a collection mycoll of documents like this :
{
vals : [10, 11]
}
where the length of the vals array is NOT fixed.
is there a way to $inc ALL the elements in the vals array with one command ?
I've tried
db.mycoll.update({}, { $inc : { vals : 5 }}, { multi : true })
// error cannot $inc non-number
db.mycoll.update({}, { $inc : { vals.$ : 5 }}, { multi : true })
// error must specify a field
and the goal is to get
{
vals : [15, 16]
}
without having to fetch each document, copy and update the array, then save the updated array back to the document...
my thanks in advance for any ideas !
whoops, there is already a JIRA open for this here
https://jira.mongodb.org/browse/SERVER-1243
You can include multiple fields in your $inc, so while you need to explicitly reference each element by its index, you can do this as:
db.mycoll.update({}, {$inc: {'vals.0': 5, 'vals.1': 5}})

Updating all elements in array [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 8 years ago.
Hey I'm trying to update all subdocuments contained within an array using the following code
setDuelToInactive: (duel) ->
Duels.update({_id: duel._id}, $set: {active: false})
userOneId = duel.userOneId
userTwoId = duel.userTwoId
Users.update({_id: userOneId}, { $set: { 'profile.character.souls.$.active': false} })
Users.update({_id: userTwoId}, { $set: { 'profile.character.souls.$.active': false} })
return
where the souls field in the Users collection is the array. I receive the following error message
MongoError: Cannot apply the positional operator without a corresponding query field containing an array.
You cannot use the positional operator $ to update al subdocuments inside an array. See the documentation: the operator matches the first element of the array that matches the query.
This also means that your query should use the array field (profile.character.souls) somehow. Yours do not, hence the error.
At this moment there is no shortcut for what you intend to do, you need to list all indexes manually. See this question: How to Update Multiple Array Elements in mongodb