I am have manually created an object in a Mongo collection:
{
"messages": [
{
"url":"http://test.test.com",
"message":"test message"
}
],
....other properties
}
I would like to add an _id:ObjectId() to each item of my messages array and for each document in the collection.
I tried:
collection.update({}, {
$set: {
'messages.$._id': ObjectId(),
},
}, { multi: true }
but this is not working. The Id is getting added when I add new ones going through Mongoose, but these were manually entered into mongo. Any help is appreciated.
Your syntax is correct, but in order to use the $ positional operator the array field must appear as part of the query document, check in documentation.
Try this:
db.collection.update({messages: {$exists: true }},
{$set: { 'messages.$._id': ObjectId() } },
{multi: true}
)
Related
This has been extensively covered here, but none of the solutions seems to be working for me. I'm attempting to remove an object from an array using that object's id. Currently, my Schema is:
const scheduleSchema = new Schema({
//unrelated
_id: ObjectId
shifts: [
{
_id: Types.ObjectId,
name: String,
shift_start: Date,
shift_end: Date,
},
],
});
I've tried almost every variation of something like this:
.findOneAndUpdate(
{ _id: req.params.id },
{
$pull: {
shifts: { _id: new Types.ObjectId(req.params.id) },
},
}
);
Database:
Database Format
Within these variations, the usual response I've gotten has been either an empty array or null.
I was able slightly find a way around this and accomplish the deletion by utilizing the main _id of the Schema (instead of the nested one:
.findOneAndUpdate(
{ _id: <main _id> },
{ $pull: { shifts: { _id: new Types.ObjectId(<nested _id>) } } },
{ new: true }
);
But I was hoping to figure out a way to do this by just using the nested _id. Any suggestions?
The problem you are having currently is you are using the same _id.
Using mongo, update method allows three objects: query, update and options.
query object is the object into collection which will be updated.
update is the action to do into the object (add, change value...).
options different options to add.
Then, assuming you have this collection:
[
{
"_id": 1,
"shifts": [
{
"_id": 2
},
{
"_id": 3
}
]
}
]
If you try to look for a document which _id is 2, obviously response will be empty (example).
Then, if none document has been found, none document will be updated.
What happens if we look for a document using shifts._id:2?
This tells mongo "search a document where shifts field has an object with _id equals to 2". This query works ok (example) but be careful, this returns the WHOLE document, not only the array which match the _id.
This not return:
[
{
"_id": 1,
"shifts": [
{
"_id": 2
}
]
}
]
Using this query mongo returns the ENTIRE document where exists a field called shifts that contains an object with an _id with value 2. This also include the whole array.
So, with tat, you know why find object works. Now adding this to an update query you can create the query:
This one to remove all shifts._id which are equal to 2.
db.collection.update({
"shifts._id": 2
},
{
$pull: {
shifts: {
_id: 2
}
}
})
Example
Or this one to remove shifts._id if parent _id is equal to 1
db.collection.update({
"_id": 1
},
{
$pull: {
shifts: {
_id: 2
}
}
})
Example
I have collection where documents have field as an array. I need to rename one field inside each item of this array, but in mongodb all variants looks very monstrous. I even try to use $[] but I can't refer to old value of object, only custom:
collection.update(
{ customField: { $exists: true } },
{
$set:
{
'payload.oneMoreField.$[].path': 'howReferToOldValue',
},
$unset:
{
'payload.oneMoreField.$[].way': '',
},
},
options
);
Somebody knows an easy way to just change the value of a key in monogodb ?
Here is my collection:
{
"_id":"5b3385af20b7dc2b008ef5b9",
"name":"C",
"distances":[{"_id":"5b3460b05b2edc1bbcb0f362",
"distance":7,
"waypoint":"5b3385af20b7dc2b008ef5b9",
"status":"available"},
{"_id":"5b3460b05b2edc1bbcb0f361",
"distance":4,
"waypoint":"5b3460a15b2edc1bbcb0f360",
"status":"available"}],
"createdAt":"2018-06-27T12:40:15.457Z",
"updatedAt":"2018-06-27T12:57:50.191Z",
"__v":0
}
Let's focus on the distances array only, so which is:
"distances":[{"_id":"5b3460b05b2edc1bbcb0f362",
"distance":7,
"waypoint":"5b3385af20b7dc2b008ef5b9",
"status":"available"},
{"_id":"5b3460b05b2edc1bbcb0f361",
"distance":4,
"waypoint":"5b3460a15b2edc1bbcb0f360",
"status":"available"}]
What i want to do is, I want to delete object and update the distances array which have "waypoint":"5b3460a15b2edc1bbcb0f360"
so far I have tried:
Model.update( {'_id': model._id}, { $pullAll: {distances: [{'waypoint': req.body.id}] } });
this isn't working. Please suggest a way out.
You can use $pull of MongoDB
db.collection.update(
{ },
{ $pull: { distances: { waypoint: req.body.id} } },
)
{multi: true}: adding this in above query will delete all entries matching { waypoint: req.body.id}
user = users.findOne({
"$or": [{
'local.email': 'some#email.com'
}, {
'google.email': 'some#email.com'
}, {
'facebook.email': 'some#email.com'
}]
// do stuff with user object
So I have the user object. This is fine, after I'm finished with what I need from it property wise I wish to update some of the fields in this object now, I've tried the following without it working:
user.local.email = 'other#email.com';
users.update(user);
Is this not a viable way of updating a document?
Use the $set operator to update your document as follows:
db.users.update(
{
"$or": [
{'local.email': 'some#email.com'},
{'google.email': 'some#email.com'},
{'facebook.email': 'some#email.com'}
]
},
{
$set: {
'local.email': 'other#email.com'
}
}
)
With the update method, you do not need to do another query which finds the document you want to update because the update() method takes in a query parameter which is the selection criteria for the update, the same query selectors as in the find() method are available. Read more on the update method in the Mongo docs here.
This was the better suited solution.
user.local.email = 'other#email.com';
users.update({
"$or": [{
'local.email': 'some#email.com'
}, {
'google.email': 'some#email.com'
}, {
'facebook.email': 'some#email.com'
}]
}, user);
I just upgraded to Mongo 2.6.1 and one update statement that was working before is not returning an error. The update statement is:
db.post.update( { 'answers.comments.name': 'jeff' },
{ '$set': {
'answers.$.comments.$.name': 'joe'
}},
{ multi: true }
)
The error I get is:
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 2,
"errmsg" : "Too many positional (i.e. '$') elements found in path 'answers.$.comments.$.createUsername'"
}
})
When I update an element just one level deep instead of two (i.e. answers.$.name instead of answers.$.comments.$.name), it works fine. If I downgrade my mongo instance below 2.6, it also works fine.
You CAN do this, you just need Mongo 3.6! Instead of redesigning your database, you could use the Array Filters feature in Mongo 3.6, which can be found here:
https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters
The beauty of this is that you can bind all matches in an array to a variable, and then reference that variable later. Here is the prime example from the link above:
Use arrayFilters.
MongoDB 3.5.12 extends all update modifiers to apply to all array
elements or all array elements that match a predicate, specified in a
new update option arrayFilters. This syntax also supports nested array
elements.
Let us assume a scenario-
"access": {
"projects": [{
"projectId": ObjectId(...),
"milestones": [{
"milestoneId": ObjectId(...),
"pulses": [{
"pulseId": ObjectId(...)
}]
}]
}]
}
Now if you want to add a pulse to a milestone which exists inside a project
db.users.updateOne({
"_id": ObjectId(userId)
}, {
"$push": {
"access.projects.$[i].milestones.$[j].pulses": ObjectId(pulseId)
}
}, {
arrayFilters: [{
"i.projectId": ObjectId(projectId)
}, {
"j.milestoneId": ObjectId(milestoneId)
}]
})
For PyMongo, use arrayFilters like this-
db.users.update_one({
"_id": ObjectId(userId)
}, {
"$push": {
"access.projects.$[i].milestones.$[j].pulses": ObjectId(pulseId)
}
}, array_filters = [{
"i.projectId": ObjectId(projectId)
}, {
"j.milestoneId": ObjectId(milestoneId)
}])
Also,
Each array filter must be a predicate over a document with a single
field name. Each array filter must be used in the update expression,
and each array filter identifier $[] must have a corresponding
array filter. must begin with a lowercase letter and not contain
any special characters. There must not be two array filters with the
same field name.
https://jira.mongodb.org/browse/SERVER-831
The positional operator can be used only once in a query. This is a limitation, there is an open ticket for improvement: https://jira.mongodb.org/browse/SERVER-831
As mentioned; more than one positional elements not supported for now. You may update with mongodb cursor.forEach() method.
db.post
.find({"answers.comments.name": "jeff"})
.forEach(function(post) {
if (post.answers) {
post.answers.forEach(function(answer) {
if (answer.comments) {
answer.comments.forEach(function(comment) {
if (comment.name === "jeff") {
comment.name = "joe";
}
});
}
});
db.post.save(post);
}
});
db.post.update(
{ 'answers.comments.name': 'jeff' },
{ '$set': {
'answers.$[i].comments.$.name': 'joe'
}},
{arrayFilters: [ { "i.comments.name": { $eq: 'jeff' } } ]}
)
check path after answers for get key path right
I have faced the same issue for the as array inside Array update require much performance impact. So, mongo db doest not support it. Redesign your database as shown in the given link below.
https://pythonolyk.wordpress.com/2016/01/17/mongodb-update-nested-array-using-positional-operator/
db.post.update( { 'answers.comments.name': 'jeff' },
{ '$set': {
'answers.$.comments.$.name': 'joe'
}},
{ multi: true }
)
Answer is
db.post.update( { 'answers.comments.name': 'jeff' },
{ '$set': {
'answers.0.comments.1.name': 'joe'
}},
{ multi: true }
)