$http.put('/api/datas/' + val[$rootScope.id]._id,val[$rootScope.id].values[0].quantity =$scope.ass);
Above mentioned is the code where val[$rootScope.id]._id is the id of the field in mongodb and val[$rootScope.id].values[0].quantity is the quantity which is to be updated and $scope.ass is the updated value.
How can I update quantity value on MongoDB ?
Try with this code for update database value :
db.databaseName.update(
{ _id: value_of_ID},
{
quantity : value_of_quantity;
},
{ upsert: true }
)
Related
So this is a fairly common scenario where I want to add unique items and preserve order in an array - I have a collection of mongo docs that follow this schema:
{
_id: ObjectID,
name: string,
email: string
favorites: [array of objectIDs]
}
I'm trying to update the favorites array only if the ID I am trying to add doesn't already exist. I also need to PRESERVE ORDER in the array and hence only want to append at the end.
I'm getting a "Cannot read property '_id' of null" error with the following update command...what am I doing wrong?
Customer.findOneAndUpdate(
{
_id: customerId, //find correct customer doc
favorites: {
$ne: itemId //only push if array doesn't already contain
}
},
{
$push: {
favorites: itemId
}
},
{ new: true} //return updated doc
)
I'm using $push to preserve order, and wanted to use the $ne operator to prevent duplicates in the customers favorites array. If I take out the favorites block it can find the doc but adds duplicates. As soon as I add in the favorites filter with the $ne, it complains with "Cannot read property '_id' of null".
Try $addToSet instead of $push.
$addToSet by default only adds to set if it is not present. For example...
{
$addToSet: {
favorites: itemId
}
}
Source: https://database.guide/mongodb-push-vs-addtoset-whats-the-difference/
Using Mongo findOneAndUpdate, I am trying to update just some fields in an object from array of objects.
My object:
mainObject:{
_id: '123',
array:[
{title:'title' , name:'name', keep:'keep'},
{title:'title', keep:'keep'},
]
}
I want to change title and name for the first object in array, and keep the keep field unchanged.
This is my closest approach using Positional Operator:
// here i set dynamic arguments for query update
// sometimes i need to update only one field, sometime i need to update more fields
// also, is there a better way to do this?
let title
let name
if (args.title) {
title = { title: args.title };
}
if (args.name) {
name= { name: args.name};
}
db.Test.findOneAndUpdate(
{ _id: args.id, 'mainObject.array.title': args.title},
{
$set: {
'mainObject.array.$[]': {
...title,
...name
}
}
}
)
this problem is that it replace the whole object, the result is:
mainObject:{
array:[
{title:'changed' , name:'changed'}, //without keep... :(
{title:'title', keep:'keep'},
]
}
Should I use aggregation framework for this?
It has to be like this :
db.test.findOneAndUpdate({'mainObject.array.title': 'title'},
{$set : {'mainObject.array.$.title':'changed','mainObject.array.$.name': 'changed'}})
From your query, $ will update the first found element in array that matches the filter query, if you've multiple elements/objects in array array then you can use $[] to update all of those, let's see your query :
'mainObject.array.$[]': {
...title,
...name
}
Major issue with above query is that it will update all the objects in array array that match the filter with below object :
{
...title,
...name
}
So, it a kind of replace entire object. Instead use . notation to update particular values.
I have flat objects stored in mongo and one of them have the field00048 attribute but my query is still returning entries without field00048. Can someone tell me what's wrong with my mongo query? I have attached a picture of the database below to show the structure.
db.QA_Book_01.find({
field00048: { $exists: true }},
{
$and:[
{ 'entryTypeId': 'Entry_Type_01' },
{ 'field00048': { $ne : 'Closed' }}]
}).count();
Out of 3 records, there is only one with the field 'field00048'. When I change the entryTypeId to Entry_Type_02, it still retrieves the record with the field 'field00048'. Not sure what's going on here.
By default, there is an and operation in find query of MongoDB so the proper syntax for applying an and operation in find query is mentioned below.
db.users.find( { $and: [ {field00048: { $exists: true }},
{ 'entryTypeId': 'Entry_Type_01' },
{ 'field00048': { $ne : 'Closed' }} ] } )
Example document:
{
"_id" : "5fTTdZhhLkFXpKvPY",
"name" : "example",
"usersActivities" : [
{
"userId" : "kHaM8hL3E3As7zkc5",
"startDate" : ISODate("2015-06-01T00:00:00.000Z"),
"endDate" : ISODate("2015-06-01T00:00:00.000Z")
}
]
}
I'm new in mongoDB and I read other questions about updating nested array and I can't do it properly. What I want to do is to change startDate and endDate for user with given userId. My problem is that it always pushes new object to array instead of changing object with given userId.
Activity.update(
_id: activityId, usersActivities: {
$elemMatch: {
userId: Meteor.userId()
}
}},
{
$push: {
'usersActivities.$.startDate': start,
'usersActivities.$.endDate': end
}
}
);
I will be really glad of help.
So the first thing to say here is the $elemMatch is not required in your case as you only want to match on a single array property. You use that operator when you need "two or more" properties from the same array element to match your conditions. Otherwise you just use "dot notation" as a standard.
The second case here is with $push, where that particular operator means to "add" elements to the array. In your case you just want to "update" so the correct operator here is $set:
Activity.update(
{ "_id": activityId, "usersActivities.userId": Meteor.userId() },
{
"$set": {
'usersActivities.$.startDate': start,
'usersActivities.$.endDate': end
}
}
)
So the positional $ operator here is what matches the "found index" from the array element and allows the $set operator to "change" the elements matched at that "position".
"What if Meteor.userId() does not exist, how to insert the whole of object with userID, startDate and endDate? – justdiehard Jun 14 at 20:20"
If you try to put new, you should take a look at Meteor Accounts package, there are methods like
Accounts.createUser(YOU_USER_SCHEME)
In my Firebase I have a entry called 'status' which has some records as 'active' and others as 'inactive'. I am trying to return all records that have the status of 'active'. I am doing the following statement.
new Firebase($rootScope.constants.firebase)
.startAt('active')
.endAt('active')
.once('value', function(snap){
console.log(snap.val());
});
However this is returning NULL.
I am adding data to firebase in the following way:
$firebase(ref).$add({
date: Firebase.ServerValue.TIMESTAMP,
status: 'active'
})
My firebase data looks like the following:
{ "-JSex4_si4a2ZMOLcEuj" : {
"date" : 1406248704619,
"status" : "active",
},
"-JShWyGQzDtAl-F8EkOI" : {
"date" : 1406291928576,
"status" : "active",
}}
Please can someone explain why I am getting NULL and how to get all records with this 'active' status?