Increment all element in nested array [duplicate] - mongodb

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 8 years ago.
I have a document like that :
{
_id: ".....",
messages: [
{
....
votes: 2
},
{
....
votes: 2
}
]
}
I would like to increment ALL votes field in the array in the same request.
How to do that ? The $ operator select only the first element.
Thank you !

You might have to do this with some JS loops:
db.collection.find( { "_id": SOME_ID } ).forEach( function( doc ) {
for ( i in doc.messages ){
doc.messages[ i ].votes += 1;
}
db.collection.save( doc );
} );
What I'm doing here is iterating over each document in the cursor and iterating over it's messages property incrementing each element's votes attribute by one.

Related

Remove element of internal field array MongoDb [duplicate]

This question already has answers here:
MongoDB, remove object from array
(7 answers)
Closed 4 years ago.
I have the following situation:
{ code: 0, array:[{ _id: 1, ....}, { _id: 2, ....}, { _id: 18, ....}]}
I need to remove the element inside 'array' field matching the '_id' field.
How can I do that?
Thank you.
Use $update & $pull:
db.yourCollection.update(
{ }, // <-- your selection criteria
{ $pull: { array: { _id: 2 } } // <-- what you want to remove from which field
)

mongodb update all document with incrementing the value by 1 [duplicate]

This question already has an answer here:
Multiple $inc updates in MongoDB
(1 answer)
Closed 4 years ago.
i have several document in mongoDB, doc structure is like this
{
"a":"abc",
"myid":2
}
I want to update "myid" of all document with 1. for example for 1st document myid = 1, for second document myid =2 and so on. Is there a query?
Try this query:
db.collection.updateMany(
{},
{$inc:{myid:1}}
)
Create a separate Collection called Counter to track the last sequence number.
db.counters.insert(
{
_id: "userid",
seq: 0
});
And create a function to fetch seq value for Counter collection.
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
});
return ret.seq;
}
And Increment your auto-increment field like below.
db.collection.insert({
"a":"abc",
"myid": getNextSequence("userid")
});
I hope this will help you.

MongoDB : Update document array value object [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 5 years ago.
I have document like below
{
_id="12345",
details:[
{
name:"Customer_Name",
time:"request_time"
},
{
name:"Customer_Name",
time:"request_time"
},
{
name:"Customer_Name",
time:"request_time"
}, ....
]
}
I want to update "name" field in all the objects of "details" array.
I can use it update each array object using
db.customer.updateMany({_id:"12345"},{$set:{"details.0.name":"My_Name"}});
Is there any way to update all of them at once
Try:
db.customer.find({ _id:"12345" })
.forEach(function (doc) {
doc.details.forEach(function (details) {
details.name="My_Name";
});
db.customer.save(doc);
});

Find the count of all the matching elements in an array [duplicate]

This question already has answers here:
Mongodb count all array elements in all objects matching by criteria
(2 answers)
Closed 4 years ago.
I need to find the count of all the matching array elements and count = 0 if the nested array do not contain values.
Here is my data entity structure.
{
name:A,
issues:[1,2,3,4]
}
{
name:B,
issues:[1,2]
}
{
name:C,
issues:[3,4]
}
If user search for issues:[1,2], I want my result set to look like
[{
name:A,
count:2
}
{
name:B,
count:2
}
{
name:C,
count:0
}]
I am using below query to achieve this but it only returns me result
[{
name:A,
count:2
}
{
name:B,
count:2
}]
which definitely I know because of the $match I am doing
{'$unwind':'$issues'}
,{'$match':{'allissues': {$in: p.issues? p.issues.map(Number):[]}}}
,{ '$group' :{_id:'$_id', name :{ $first: '$name' },count: { $sum: 1 }} }'
Given that issues variable is the array input by users, you do not need to use a three-stages aggregation like above to get the result. You just need to find the intersection of users input and issues field of each document, then get length of the result arrays. This code will do the job:
db.col.aggregate([{
$project: {
count: {
$size: {
$setIntersection: [issues, "$issues"]
}
}
}
}])

mongodb: insert item into array only if a certain field is not present [duplicate]

This question already has answers here:
Can you specify a key for $addToSet in Mongo?
(2 answers)
Closed 8 years ago.
I have a data model which looks like this
{
_id: 1
some_property: some_value
items: [
{
item_id: item1
item_properties: [
{
key1: val1,
key2: val2
}]
}]
}
When I get a new item with item_id=itemX, I would like to check if an item with this item_id is in the items array. If it's not present, then insert it. If it is present, i would like to append the item_properties to the existing item_properties.
I tried using $addToSet, but this considers the entire item and not the item_id itself. So the result was 2 items with the same item_id.
Any idea how i can achieve this atomically?
Thanks,
Aliza
The following codes can run atomically, I think.
function doWhenItemExisted() {
var n = db.c.update({
"items.item_id" : itemX
}, {
$pushAll: { // I think item_properties of given item is also an array
"items.$.item_properties" : item.item_properties
}
}).nModified;
if (!n) {
doWhenItemNotExisted();
}
}
function doWhenItemNotExisted() {
var n = db.c.update({
"items.item_id" : {
$ne : itemX
}
}, {
$push: {
"items" : item
}
}).nModified;
if (!n) {
doWhenItemExisted();
}
}
// entry
doWhenItemExisted();