$inc not working mongoDB - mongodb

I have a MongoDB data like this
{
_id: "5aa8f087e1eee70004a99e1d"
users: [{facebookId: "-1", unread: 0},{facebookId: "323232321", unread: 1}]
}
I want to increment users.unread where facebookId in not "-1"
I tried this query
chat.update({ "_id": { "$in": chatId }, "users.facebookId": { "$ne": "-1" } },{"$inc": { "users.$.unread": 1 } }, { multi: true, upsert: true }, function(err, data) {
if (err) throw err;
console.log(data);
});

From MongoDB docs:
If the query matches the array using a negation operator, such as $ne, $not, or $nin, then you cannot use the positional operator to update values from this array.
However, if the negated portion of the query is inside of an $elemMatch expression, then you can use the positional operator to update this field
Below code should work if you want to increment first matching element:
db.chat.update({ "_id":"5aa8f087e1eee70004a99e1d", "users": { $elemMatch: { "facebookId": { "$ne": "-1" } }}},{"$inc": { "users.$.unread": 1 }})
Otherwise you can use array filters in MongoDB 3.6
db.col.update({ "_id":"5aa8f087e1eee70004a99e1d" }, { "$inc" : { "users.$[cond].unread" : 1 } }, { arrayFilters: [ { "cond.facebookId": { $ne: "-1" } } ] })

Related

MongoDB - Update the value of one field with the value of another nested field

I am trying to run a MongoDB query to update the value of one field with the value of another nested field. I have the following document:
{
"name": "name",
"address": "address",
"times": 10,
"snapshots": [
{
"dayTotal": 2,
"dayHit": 2,
"dayIndex": 2
},
{
"dayTotal": 3,
"dayHit": 3,
"dayIndex": 3
}
]
}
I am trying like this:
db.netGraphMetadataDTO.updateMany(
{ },
[{ $set: { times: "$snapshots.$[elem].dayTotal" } }],
{
arrayFilters: [{"elem.dayIndex":{"$eq": 2}}],
upsert: false,
multi: true
}
);
but got an error:
arrayFilters may not be specified for pipeline-syle updates
You can't use arrayFilters with aggregation pipeline for update query at the same time.
Instead, what you need to do:
Get the dayTotal field from the result 2.
Take the first matched document from the result 3.
Filter the document from snapshots array.
db.netGraphMetadataDTO.updateMany({},
[
{
$set: {
times: {
$getField: {
field: "dayTotal",
input: {
$first: {
$filter: {
input: "$snapshots",
cond: {
$eq: [
"$$this.dayIndex",
2
]
}
}
}
}
}
}
}
}
],
{
upsert: false,
multi: true
})
Demo # Mongo Playground

mongo $or to return a single document base don first critera

I have the following query:
db.getCollection('MyCollection').find({
$or: [{
"Zips": {
$elemMatch: { "ZipCode5": "95757" , "ZipCode4": "6237"}
}
}, {
"Zips": {
$elemMatch: { "ZipCode5": "95757" , "ZipCode4": "0000"}
}
}]
})
I have both documents on my collection, but I want only to return the document that matches the first criteria if both exist, and the 2nd if the first dosn't exist.
Currently, the above query returns both if they both exist.
Why not just limit to first row then?..
db.getCollection('MyCollection').find({
$or: [{
"Zips": {
$elemMatch: { "ZipCode5": "95757" , "ZipCode4": "6237"}
}
}, {
"Zips": {
$elemMatch: { "ZipCode5": "95757" , "ZipCode4": "0000"}
}
}]
}).limit(1)

MongoDB - Update or Insert object in array

I have the following collection
{
"_id" : ObjectId("57315ba4846dd82425ca2408"),
"myarray" : [
{
userId : ObjectId("570ca5e48dbe673802c2d035"),
point : 5
},
{
userId : ObjectId("613ca5e48dbe673802c2d521"),
point : 2
},
]
}
These are my questions
I want to push into myarray if userId doesn't exist, it should be appended to myarray. If userId exists, it should be updated to point.
I found this
db.collection.update({
_id : ObjectId("57315ba4846dd82425ca2408"),
"myarray.userId" : ObjectId("570ca5e48dbe673802c2d035")
}, {
$set: { "myarray.$.point": 10 }
})
But if userId doesn't exist, nothing happens.
and
db.collection.update({
_id : ObjectId("57315ba4846dd82425ca2408")
}, {
$push: {
"myarray": {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
})
But if userId object already exists, it will push again.
What is the best way to do this in MongoDB?
Try this
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{ $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{ $push: {"myarray": {
userId:ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}}
)
Explination:
in the first statment $pull removes the element with userId= ObjectId("570ca5e48dbe673802c2d035") from the array on the document where _id = ObjectId("57315ba4846dd82425ca2408")
In the second one $push inserts
this object { userId:ObjectId("570ca5e48dbe673802c2d035"), point: 10 } in the same array.
The accepted answer by Flying Fisher is that the existing record will first be deleted, and then it will be pushed again.
A safer approach (common sense) would be to try to update the record first, and if that did not find a match, insert it, like so:
// first try to overwrite existing value
var result = db.collection.update(
{
_id : ObjectId("57315ba4846dd82425ca2408"),
"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")
},
{
$set: {"myarray.$.point": {point: 10}}
}
);
// you probably need to modify the following if-statement to some async callback
// checking depending on your server-side code and mongodb-driver
if(!result.nMatched)
{
// record not found, so create a new entry
// this can be done using $addToSet:
db.collection.update(
{
_id: ObjectId("57315ba4846dd82425ca2408")
},
{
$addToSet: {
myarray: {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
}
);
// OR (the equivalent) using $push:
db.collection.update(
{
_id: ObjectId("57315ba4846dd82425ca2408"),
"myarray.userId": {$ne: ObjectId("570ca5e48dbe673802c2d035"}}
},
{
$push: {
myarray: {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
}
);
}
This should also give (common sense, untested) an increase in performance, if in most cases the record already exists, only the first query will be executed.
There is a option called update documents with aggregation pipeline starting from MongoDB v4.2,
check condition $cond if userId in myarray.userId or not
if yes then $map to iterate loop of myarray array and check condition if userId match then merge with new document using $mergeObjects
if no then $concatArrays to concat new object and myarray
let _id = ObjectId("57315ba4846dd82425ca2408");
let updateDoc = {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
};
db.collection.update(
{ _id: _id },
[{
$set: {
myarray: {
$cond: [
{ $in: [updateDoc.userId, "$myarray.userId"] },
{
$map: {
input: "$myarray",
in: {
$mergeObjects: [
"$$this",
{
$cond: [
{ $eq: ["$$this.userId", updateDoc.userId] },
updateDoc,
{}
]
}
]
}
}
},
{ $concatArrays: ["$myarray", [updateDoc]] }
]
}
}
}]
)
Playground
Unfortunately "upsert" operation is not possible on embedded array. Operators simply do not exist so that this is not possible in a single statement.Hence you must perform two update operations in order to do what you want. Also the order of application for these two updates is important to get desired result.
I haven't found any solutions based on a one atomic query. Instead there are 3 ways based on a sequence of two queries:
always $pull (to remove the item from array), then $push (to add the updated item to array)
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{ $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{
$push: {
"myarray": {
userId:ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
}
)
try to $set (to update the item in array if exists), then get the result and check if the updating operation successed or if a $push needs (to insert the item)
var result = db.collection.update(
{
_id : ObjectId("57315ba4846dd82425ca2408"),
"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")
},
{
$set: {"myarray.$.point": {point: 10}}
}
);
if(!result.nMatched){
db.collection.update({_id: ObjectId("57315ba4846dd82425ca2408")},
{
$addToSet: {
myarray: {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
);
always $addToSet (to add the item if not exists), then always $set to update the item in array
db.collection.update({_id: ObjectId("57315ba4846dd82425ca2408")},
myarray: { $not: { $elemMatch: {userId: ObjectId("570ca5e48dbe673802c2d035")} } } },
{
$addToSet : {
myarray: {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
},
{ multi: false, upsert: false});
db.collection.update({
_id: ObjectId("57315ba4846dd82425ca2408"),
"myArray.userId": ObjectId("570ca5e48dbe673802c2d035")
},
{ $set : { myArray.$.point: 10 } },
{ multi: false, upsert: false});
1st and 2nd way are unsafe, so transaction must be established to avoid two concurrent requests could push the same item generating a duplicate.
3rd way is safer. the $addToSet adds only if the item doesn't exist, otherwise nothing happens. In case of two concurrent requests, only one of them adds the missing item to the array.
Possible solution with aggregation pipeline:
db.collection.update(
{ _id },
[
{
$set: {
myarray: { $filter: {
input: '$myarray',
as: 'myarray',
cond: { $ne: ['$$myarray.userId', ObjectId('570ca5e48dbe673802c2d035')] },
} },
},
},
{
$set: {
myarray: {
$concatArrays: [
'$myarray',
[{ userId: ObjectId('570ca5e48dbe673802c2d035'), point: 10 },
],
],
},
},
},
],
);
We use 2 stages:
filter myarray (= remove element if userId exist)
concat filtered myarray with new element;
When you want update or insert value in array try it
Object in db
key:name,
key1:name1,
arr:[
{
val:1,
val2:1
}
]
Query
var query = {
$inc:{
"arr.0.val": 2,
"arr.0.val2": 2
}
}
.updateOne( { "key": name }, query, { upsert: true }
key:name,
key1:name1,
arr:[
{
val:3,
val2:3
}
]
In MongoDB 3.6 it is now possible to upsert elements in an array.
array update and create don't mix in under one query, if you care much about atomicity then there's this solution:
normalise your schema to,
{
"_id" : ObjectId("57315ba4846dd82425ca2408"),
userId : ObjectId("570ca5e48dbe673802c2d035"),
point : 5
}
You could use a variation of the .forEach/.updateOne method I currently use in mongosh CLI to do things like that. In the .forEach, you might be able to set all of your if/then conditions that you mentioned.
Example of .forEach/.updateOne:
let medications = db.medications.aggregate([
{$match: {patient_id: {$exists: true}}}
]).toArray();
medications.forEach(med => {
try {
db.patients.updateOne({patient_id: med.patient_id},
{$push: {medications: med}}
)
} catch {
console.log("Didn't find match for patient_id. Could not add this med to a patient.")
}
})
This may not be the most "MongoDB way" to do it, but it definitely works and gives you the freedom of javascript to do things within the .forEach.

Mongoose elemMatch and inc query based on id

How am I going to write mongoose function that will query this mongo query based on a given userId (I could not add this to query, also need that).
db.users.update({ categories : { $elemMatch: { name: "Sport" } } },
{$inc: {"categories.$.points": 6666, points : 7777}})
That doesn't help me out.
User.findByIdAndUpdate(
request.params.userId,
//{ $inc: { points: 1 }},
{ categories : { $elemMatch: { name: "Spor" }}},
{$inc: {"categories.$.points": 6666, points : 7777}},
//{ safe: true, upsert: true, new : true },
function(err, user) {
if (!err) {
return reply(user); // HTTP 201
}
if (11000 === err.code || 11001 === err.code) {
return reply(Boom.forbidden("please provide another user id, it already exist!"));
}
return reply(Boom.forbidden(err)); // HTTP 403
}
);
You need to use findOneAndUpdate instead of findByIdAndUpdate if you want to match on anything beyond just the _id. You also don't need to use $elemMatch here as you're only matching against a single field in the categories array so a simple dot notation field match can be used instead.
So it should be:
User.findOneAndUpdate(
{ _id: request.params.userId, "categories.name": "Sport" },
{ $inc: { "categories.$.points": 6666, points : 7777 }},
{ safe: true, upsert: true, new: true },
function(err, user) { ... }
);

How do i make logical operation $or on array field in mongo db

In a MongoDB collection, I have some data after an aggregation:
{
"_id" : ObjectId("5411e00c0d42e2a3688b47d3"),
"found" : [false, false, false, false],
}
How can I do the logical OR on array "found", to get true if any of elements is set to true, оf false if all elements are false?
I'm trying this, but it always returns true:
db.test.aggregate( {
$project:
{
found: { $or: "$found" }
}
});
// "result" : [
// {
// "_id" : ObjectId("5411e00c0d42e2a3688b47d3"),
// "found" : true
// }
// ],
P.S. I am using MongoDB 2.6
Starting from version 2.6 you can use $anyElementTrue:
db.test.aggregate({
$project: {
like: { $anyElementTrue: ["$found"] }
}
});
See this:
http://docs.mongodb.org/manual/reference/operator/aggregation/anyElementTrue/#exp._S_anyElementTrue
If you use earlier version then I'm afraid that you'll have to use either map/reduce or $unwind -> $group combination. Something like that:
db.test.aggregate([
{
$unwind: "found"
},
{
$group: {
_id: "_id",
like: { $or: "found" }
}
}
]);