Only update mongo document if value is bigger - javascript

I got a collection of documents in mongo DB.
One of the fields in the document is "verison" : int
I was wondering if there is a practical way to use this value to prevent update of the document when there is an attempt to update it with the same or smaller version number.
example :
my collection has a document :
{
"name": "john",
"version": 3
}
if I try to send update with :
{
"name": "rick"
"version": 3
}
It wont update it, and I will get an indication that there was no update so I can handle this in some way in my code.
I am using node.js with native mongo DB driver.

You can solve using the below Code.
db.collection.update({'version':{$gte : 3}},{$set : {name:'Abc'}},{upsert : true,new:true})

Related

Node - Mongoose update method issue

I need to update and already queried document:
In memory save way works fine:
project.likers.push(profile.id);
project.set({
likes: project.likes + 1
})
await project.save();
But I read in a blog that this way is slower as compared to using mongoose update method.
Since I am using multiple queries in this endpoint, I want to use mongoose update method for the same reason.
Doesn't work
project.update({ "$push": { "likers": profile.id }, "$inc": { "likes": 1 } });
Thanks in advance!
$push : The operator appends a specified value to an array.
And there isn't command 'update'. There are two command for update and they are :
updateOne
updateMany
If you just want to update the existing field, you can use like below:
db.collectionname.updateMany({ "likers": profile.id }, { "$inc": { "likes": 1 } })
If you want more info, check out.

aws personalize putevents does not update recommendations

I'm trying to use AWS Personalize. After creating dataset and batch inference, I am updating the user-item-interactions with personalize.putEvents (using Javascript SDK, docs)
Snippet:
const awsOpts = { apiVersion, accessKeyId, secretAccessKey, region }
const pEvents = new AWS.PersonalizeEvents(awsOpts)
// ...
const params = {
trackingId, userId, sessionId,
eventList: [{
eventId: (+sentAt) + "",
sentAt,
eventType,
properties: { itemId }
}]
}
pEvents.putEvents(params, (err, data) => err ? reject(err) : resolve(data))
The events seem to be registered. No errors. After that when I create another batch-inference, I would expect that the new user-items would not appear in the recommendations anymore. But the recommendations in the next batch-inference are unchanged. Am I doing something wrong or am I misunderstanding the putEvents-API-call?
Schema for reference:
{
"type": "record",
"name": "Interactions",
"namespace": "com.amazonaws.personalize.schema",
"fields": [
{
"name": "USER_ID",
"type": "string"
},
{
"name": "ITEM_ID",
"type": "string"
},
{
"name": "EVENT_TYPE",
"type": "string"
},
{
"name": "TIMESTAMP",
"type": "long"
}
],
"version": "1.0"
}
One thing seems a bit strange: Cloud watch reports that the lambda was executed twice despite no errors nor timeout exceeded (timeout is set to 10s, and the lambda takes less than 2s). Also Retry attempts is set to 2.
#D.J.Duff (sadly I can't comment)
Are you sure the events added using PutEvent API are considered without retraining ? I have been through the AWS Personalize Doc looking for exactly that and it looked to me that you need to retrain to get those events included and for the runtime api to be able to consider them. Could you point to me where you saw that they are considered without having to retrain ? Thanks
User-item recommendations, at least from the runtime API should change without retraining after some events (that is what it is for and that is how we use it), though perhaps (it is something to check) you need to use the runtime API to see the new recommendations.
(edited to clarify that that the API is called the "runtime" API - thanks to PatrykMilewski for seeking the clarification - and that I am by no means certain that the particular API used is the important thing - I do know that when using the runtime API, the events do have an effect though).
I have tried out the very same usecase with personalize using boto3 sdk. Yes!! Put events can be used to update user-item-interactions. No need to retrain the model after put events. Looks like aws personalize solutions are made compatible to handle the data updated with put events. When I run the next batch inference, after updating interactions with put events API, I could see the change in the recommendations. I verified this with personalized ranking recipe. I could see the recent interacted items getting re-ranked according users recent interactions.

Mongo command to fech records based on the field present inside json object

I'm using MongoDB and I have a signed data collection and the record is of below format:
{
"_id" : "50000235-01",
"requiredDocs" : {
"docSigned": "Y",
"responseCode" : "0"
}
}
Now I want to fetch all the records where I have:
"docSigned": "N"
I'm using robo3t tool to connect to MongoDB and fetching the record. Can someone help with the mongo MongoDB in fetching this type?
db.getCollection('signeddata').find({}).sort({$natural:-1})
Can someone help with the condition given with in find({})
This is resolved.I've used below command and it worked.
db.getCollection('signeddata').find({'requiredDocs.docSigned':'N'}).sort({$natural:-1})

Firebase returns the entire database even with setting ref url

I am trying to setup Firebase's realtime database in my web app.
I have everything initialized properly and can connect to the database. However, when I try to fetch data, I get the entire database returned in the snapchat.
The code I have here is trying to determine if a key exists:
var ref = firebase.database().ref('cars/');
ref.once('value', function (snapshot) {
if (snapshot.hasChild('toyota')) {
alert('exists');
} else {
alert('does not exist');
}
});
This always displays the 'does not exist' dialog, so when I ran:
alert(JSON.stringify(snapshot));
I realized that firebase was fetching everything.
Here is the structure of my database:
{
"users": {
"uid": {
"name": "John Doe",
"balance": 500
}
},
"cars": {
"carid": {
"name": "Name of Car",
"cost": "250",
"features": [
"ac", "awd", "leather_seats"
]
}
}
}
Does anybody know how to fix this? Every request I make just returns the entire database, which is frustrating. Thanks.
Hey try using the child method to access your nodes
var ref = firebase.database().ref().child('/cars');
Sorry there was some missing bits.
I retrieve data for a node in the following way, without the preceding or trailing slash. Check if the following works.
var ref = firebase.database().ref().child('cars');
For some reason firebase had an entire duplicate of the database placed under the node, so in actuality I was fetching the data from the specific node, it just so happened that it contained a copy of the database.
What I'm curious about is to how this could happen, as I was under the impression that when you imported JSON into firebase, it overwrote the entire database.

Meteor.js update only one parameter instead of whole collection

I'm trying to mark message as readed using code below :
Template.FullMessage.onRendered(function () {
var id = FlowRouter.getParam('id');
Messages.update(id, {$set: {readed: true} });
});
Collection is :
"_id": "YMxYn9NodPeZqFP83",
"whatAbout": "adsfadsfasdf",
"message": "sdfadsfadfadsfasdfasdf",
"recipientId": "9ewiF8JTNp77Pmijw",
"author": "9ewiF8JTNp77Pmijw",
"createdAt": "2016-05-09T08:37:52.282Z",
"owner": "seofilms",
"readed": false
}
I expected that column "readed":"false" will be replaced with "readed":true,
but instead of it, everything in here is changing, including owner. So for instance if I will open message with user test, I will change also the owner of this message.
Why does it happens ?
Is it possible to prevent sending whole object and change it only with ID?
Thank you for any ideas.
Try this:
Messages.update({_id: id}, {$set: {readed: true} });
It should also work with only id, as you're already doing. Is there any other code that's writing to the same collection? Try to run it in console and check if it's still updating all the properties.

Categories

Resources