I have a data that looks like below in MongoDB
{
_id: aasdfeasfeasdf,
todo: [
{_todoIde: 333, _with: []},
{_todoIde: 111, _with: []},
]
}
I want to $addToSet value to _todoIde: 333's _with like {_todoIde: 333, _with: [aaaa]},. How can I do it?
.updateOne(
{_id},
{ $addToSet: {}}
)
I got to the document but I can't specify that _todoIde: 333 to update just that one.
The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array,
.updateOne(
{ _id: "aasdfeasfeasdf", "todo._todoIde": 333 },
{
$addToSet: {
"todo.$._with": "aaaa"
}
}
)
Playground
You have to add an extra condition to specify the todoIde
Try this:
db.collection.update(
{$and:[{_id: typeId},{'todo._todoIde': 333}]},
{$set: { "todo._todoIde.$._with":[a,b,c]}},
);
Related
I have a group collection that has the array order that contains ids.
I would like to use updateOne to set multiple items in that order array.
I tried this which updates one value in the array:
db.groups.updateOne({
_id: '831e0572-0f04-4d84-b1cf-64ffa9a12199'
},
{$set: {'order.0': 'b6386841-2ff7-4d90-af5d-7499dd49ca4b'}}
)
That correctly updates (or sets) the array value with index 0.
However, I want to set more array values and updateOne also supports a pipeline so I tried this:
db.slides.updateOne({
_id: '831e0572-0f04-4d84-b1cf-64ffa9a12199'
},
[
{$set: {'order.0': 'b6386841-2ff7-4d90-af5d-7499dd49ca4b1'}}
]
)
This does NOTHING if the order array is empty. But if it's not, it replaces every element in the order array with an object { 0: 'b6386841-2ff7-4d90-af5d-7499dd49ca4b1' }.
I don't understand that behavior.
In the optimal case I would just do
db.slides.updateOne({
_id: '831e0572-0f04-4d84-b1cf-64ffa9a12199'
},
[
{$set: {'order.0': 'b6386841-2ff7-4d90-af5d-7499dd49ca4b1'}},
{$set: {'order.1': 'otherid'}},
{$set: {'order.2': 'anotherone'}},
]
)
And that would just update the order array with the values.
What is happening here and how can I achieve my desired behavior?
The update by index position in the array is only supported in regular update queries, but not in aggregation queries,
They have explained this feature in regular update query $set operator documentation, but not it aggregation $set.
The correct implementation in regular update query:
db.slides.updateOne({
_id: '831e0572-0f04-4d84-b1cf-64ffa9a12199'
},
{
$set: {
'order.0': 'b6386841-2ff7-4d90-af5d-7499dd49ca4b1',
'order.1': 'otherid',
'order.2': 'anotherone'
}
}
)
If you are looking for only an aggregation query, it is totally long process than the above regular update query, i don't recommend that way instead, you can format your input in your client-side language and use regular query.
If you have to use aggregation framework, try this (you will have to pass array of indexes and array of updated values separately):
$map and $range to iterate over the order array by indexes
$cond and $arrayElemAt to check if the current index is in the array of indexes that has to be updates. If it is, update it with the same index from the array of new values. If it is not, keep the current value.
NOTE: This will work only if the array of indexes that you want to update starts from 0 and goes up (as in your example).
db.collection.update({
_id: '831e0572-0f04-4d84-b1cf-64ffa9a12199'
},
[
{
"$set": {
"order": {
"$map": {
input: {
$range: [
0,
{
$size: "$order"
}
]
},
in: {
$cond: [
{
$in: [
"$$this",
[
0,
1,
2
]
]
},
{
$arrayElemAt: [
[
"b6386841-2ff7-4d90-af5d-7499dd49ca4b1",
"otherid",
"anotherone"
],
"$$this"
]
},
{
$arrayElemAt: [
"$order",
"$$this"
]
}
]
}
}
}
}
}
])
Here is the working example: https://mongoplayground.net/p/P4irM9Ouyza
I want to be able to query a field that does not contain any of the elements in an array.
for example, I have an array of objects (venue) :
db.collection.aggregate([{ $match: { roomNo: {$ne:venue}}},
])
how shall I access the array in the object and query using $ne?
Is there a way to do this?
I was not able to achieve what I wanted using the above method.
Use $nin in the query
For Eg: db.collection.find( { roomNo: { $nin: [ 5, 15 ] } } )
This example works:
db.collection.save({ roomNo : 1, floor : 1})
db.collection.save({ roomNo : 2, floor : 1})
db.collection.save({ roomNo : 3, floor : 1})
db.collection.aggregate([
{
$addFields: {venue: [2,3]}
},
{
$match: { roomNo: {$nin : venue}}
}
])
try it
I have a mongoose model in which some fields are like :
var AssociateSchema = new Schema({
personalInformation: {
familyName: { type: String },
givenName: { type: String }
}
})
I want to perform a '$regex' on the concatenation of familyName and givenName (something like 'familyName + " " + 'givenName'), for this purpose I'm using aggregate framework with $concat inside $project to produce a 'fullName' field and then '$regex' inside $match to search on that field. The code in mongoose for my query is:
Associate.aggregate([
{ $project: {fullName: { $concat: [
'personalInformation.givenName','personalInformation.familyName']}}},
$match: { fullName: { 'active': true, $regex: param, $options: 'i' } }}
])
But it's giving me error:
MongoError: $concat only supports strings, not double on the first
stage of my aggregate pipeline i.e $project stage.
Can anyone point out what I'm doing wrong ?
I also got this error and then discovered that indeed one of the documents in the collection was to blame. They way I fished it out was by filtering by field type as explained in the docs:
db.addressBook.find( { "zipCode" : { $type : "double" } } )
I found the field had the value NaN, which to my eyes wouldn't be a number, but mongodb interprets it as such.
Looking at your code, I'm not sure why $concat isn't working for you unless you've had some integers sneak into some of your document fields. Have you tried having a $-sign in front of your concatenated values? as in, '$personalInformation.givenName'? Are you sure every single familyName and givenName is a string, not a double, in your collection? All it takes is one double for your $concat to fold.
In any case, I had a similar type mismatch problem with actual doubles. $concat indeed supports only strings, and usually, all you'd do is cast any non-strings to strings.. but alas, at the time of this writing MongoDB 3.6.2 does not yet support integer/double => string casting, only date => string casting. Sad face.
That said, try adding this projection hack at the top of your query. This worked for me as a typecast. Just make sure you provide a long enough byte length (128-byte name is pretty long so you should be okay).
{
$project: {
castedGivenName: {
$substrBytes: [ 'personalInformation.givenName', 0, 128 ]
},
castedFamilyName: {
$substrBytes: [ 'personalInformation.familyName', 0, 128 ]
}
},
{
$project: {
fullName: {
$concat: [
'$castedGivenName',
'$castedFamilyName'
]
}
}
},
{
$match: { fullName: { 'active': true, $regex: param, $options: 'i' } }
}
I managed to make it work by using $substr method, so the $project part of my aggregate pipeline is now:
`$project: {
fullName: {
$concat: [
{ $substr: ['$personalInformation.givenName', 0, -1] }, ' ', { $substr: ['$personalInformation.familyName', 0, -1] }
]
}
}
}`
I'm looking to $push something into a nested array, of which the parent array matches a simple property condition:
Here's how my document looks:
{
name: "Foo",
boardBucket: {
currentBoardId: 1234,
items: [ <- looking to push into `boardItems` of an `item` in this Array
{
boardId: 1234, <- that has `boardId: 1234`
boardItems: [ "barItem", "deyItem" ] <- Final Array I want to push to
}
]
}
}
So I'd like to push "fooItem" in boardItems of item that has boardId: 1234
Option 1: I can use dot notation and access by index
I can certainly do a $push by using dot.notation which uses the index of the item like so:
this.update({ '$push': {"boardBucket.items.0.boardItems": "fooItem" } });
But what if I don't know the index?
How can I push into boardItems of item with boardId: 1234 without using the indices (using the boardId instead)?
Note:
I'm using mongoose as the db driver
I'd like to avoid using mongoose's save() cause it tends to be buggy + it seems to keep a copy of the object locally which i'd like to avoid
Just direct update() mongo queries are what I'm after
I'd certainly like to avoid any type of whole-document fetching to perform this update as my documents are huge in size
I think this should do the trick:
this.update(
{"boardBucket.items": {$elemMatch: { boardId: "1234"}}},
{'$push': {"boardBucket.items.boardItems": "fooItem" }}
);
(Sorry for not sampling in the first place, was on a rush then)
db.myDb.insert({
name: "Foo",
boardBucket: {
currentBoardId: 1234,
items: [
{
boardId: 1234,
boardItems: [ "barItem", "deyItem" ]
},
{
boardId: 1235,
boardItems: [ "dontPushToThisOne" ]
}
]
}
});
db.myDb.insert({
name: "Foo2",
boardBucket: {
currentBoardId: 1236,
items: [
{
boardId: 1236,
boardItems: [ "dontPushToThisOne" ]
}
]
}
});
db.myDb.update(
{ "boardBucket.currentBoardId":1234,
"boardBucket.items.boardId":1234},
{ "$push" : {"boardBucket.items.$.boardItems":"fooItem"} }, {multi:1} );
i have a Mongodb collection named "EVENTS" and in the collection i have an object of array which looks like this:
{
"Events":[
{
"_id":"53ae59883d0e63aa77f7b5b2",
"Title":"Title Blank",
"Desc":"Description Blank",
"Date":"2014-06-04 00:30",
"Link":"http://googleparty.com",
"Event":"Victoria Centre",
"dateCreated":"28/6/2014 06:58"
},
{
"_id":"53ae59883d0e63aa77f7b5b3",
"Title":"Hello World",
"Desc":"hello",
"Date":"2014-06-04 00:30",
"Link":"http://linkedinparty.com",
"Event":"social",
"dateCreated":"30/2/2014 11:10"
}
]
}
how would i delete an object by id in node.js so " delete(53ae59883d0e63aa77f7b5b2)" will yield this:
{
"Events":[
{
"_id":"53ae59883d0e63aa77f7b5b3",
"Title":"Hello World",
"Desc":"hello",
"Date":"2014-06-04 00:30",
"Link":"http://linkedinparty.com",
"Event":"social",
"dateCreated":"30/2/2014 11:10"
}
]
}
Regards
If all you really want to do is "empty" the array then you just need to use the $set operator with an .update() and "set" the array as an empty one:
db.collection.update({},{ "$set": { "Events": [] } },{ "mutli": true})
So the .update() operation takes a "query" to select the documents in your collection, a blank query as shown selects everything. The "update" section contains the $set operation that just replaces the current "Events" field with an empty array.
The "multi" option there makes sure this is applied to every document that matches. The default is false and will only update the first document that matches.
For more specific operations removing selected array elements, look at the $pull operator. Your edit shows now that this is what you want to do:
db.collection.update(
{ "Events._id": ObjectId("53ae59883d0e63aa77f7b5b2") },
{ "$pull": { "Events": { "_id": ObjectId("53ae59883d0e63aa77f7b5b2") } } }
)
But your inclusion of arrays with _id fields seems to indicate that you are using mongoose, so the ObjectId values are cast automatically:
Model.update(
{ "Events._id": "53ae59883d0e63aa77f7b5b2" },
{ "$pull": { "Events": { "_id": "53ae59883d0e63aa77f7b5b2" } } },
function(err,numAffected) {
}
);