Polls.update({_id: id}, {$set : {already_voted[length]: ip});
Now this obviously doesn't work. I can't simply put a variable "length" in there.
Basically I have already_voted which is an array and I want to add a new ip to this array. The way I handle this currently is by getting the old length and using the old length as the new index to add the element.
I am wondering how I should go about doing this as my current setup does not work.
To clarify : I don't have the whole array, I just want to add a new element into the array in the Poll document.
Use the $push Mongo operator:
Polls.update({ _id: id },{ $push: { already_voted: ip }})
See the docs here.
It is quite easy to add element to array in collection in meteor:
collection.update({_id: "unique id"},{$push:{already_voted: ip}});
You can even user upsert instead of update as per you requirement.
something like this:
collection.upsert({_id: "unique id"},{$push:{already_voted: ip}});
Related
I want to check in a db if 'test' exists in a document, in a specific field. If exists, I want to increment it by 1, to look like this 'test-1', and then check again in the db, and repeat until it's not found, than save it there.
I don't have a problem with the increment part, just with the mongoose/mongodb part where I need to re-query with the new value. Is there any way that can be done in the same query, multiple times?
Edited: I want to create a new field based on the name, but I want this field to be unique, because I want to use it as an id.
So, for instance, if I have something like name: 'John Smith' I want to create a new field in my document like this: uniqueId: john-smith, for the same document. The problem is, if another John Smith is inserted in my collection, I want to check if the uniqueId john-smith is available, if not I want to append a -1 to it, so it will look like this john-smith-1, and so on, until a john-smith-(number) is not found, then I will know the id is unique and save it to the document.
One idea would be to use a Model.find() inside of a recursive function with the uniqueId, and repeat until a document is not found. But I was wondering if there might be another way, maybe something less complicated?
mongodb v4.2.3
I have a firestore firebase database , in which I have a collection users
there is an array in the collection and in the array there is a map
in map there is a field qty.. I want to increment that qty value..
using increment doesnt help as the qty is inside a array index
db.collection("users").doc(checkId).update({
myCart: firebase.firestore.FieldValue.arrayUnion({
qty: firebase.firestore.FieldValue.increment(1),
}),
this is the error Output =>
Uncaught (in promise) FirebaseError: Function FieldValue.arrayUnion() called with invalid data. FieldValue.increment() can only be used with update() and set()
My answer below won't work, given that the qty is in an array. The only way to update an item in an array is to read the entire document, update the item in the array, and then write the entire array with the updated item back to the document.
An alternative would be to use a map instead of an array, and then update the qty using the approach outlined in my (old, and non-working) answer below 👇
You need to specify the full path to the field you're trying to update. So I think in your case, that'll be:
db.collection("users").doc(checkId).update({
"myCart.0.qty": firebase.firestore.FieldValue.increment(1)
}),
The field you want to update is embedded in an array. In this case, you can't use FieldValue.increment(), since it's not possible to call out an array element as a named field value.
What you'll have to do instead is read the entire document, modify the field in memory to contain what you want, and update the field back into the document. Also consider using a transaction for this if you need to update to be atomic.
(If the field wasn't part of an array, you could use FieldValue.increment().)
As of today (29-04-2020)... this is tested by me.
Suppose my data structure is like this:
collection: Users
Any document: say jdfhjksdhfw
It has a map like below
map name: UserPageVisits
map fields: field1,field2,field3 etc
Now we can increment the number field in the map like below:
mapname.field1 etc...
That is use the dot operator to access the fields inside the map just like you would do to an object of javascript.
JAVA Code (Android), update the field using transactions so they can complete atomically.
transaction.update(<documentreference object>,"UserPageVisits.field1",FieldValue.increment(1));
I have just pushed a version of my app which uses this concept and it's working.
Kudos !!
My Best Regards
Previous answers helped me as well, but dont forget about the "merge" property!!! Otherwise it will overwrite your entire array, losing other fields.
var myIndex = 0;
const userRef = db.collection('users').doc(checkId);
return userRef.update({
'myCart.${myIndex}.qty': admin.firestore.FieldValue.increment(1)
}, {
merge: true
});
I'm using Firebase and Vuejs to create an database element, which has object array inside.
That's how the field looks, and I want to add tasks through the form into the 'moreTasks' as an array.
I tried using this, but it just creates new entity in the database.
db.collection('Tasks').add({
tasker: this.tasker.taskerName
})
I also tried checking API but I couldnt understand the refs, because I was using different methods to achieve that goal.
creatTask() {
db.collection('Tasks').add({
task_id: this.task_id,
name: this.name,
What would be correct way to approach this problem?
You can append an item to an array using FieldValue.arrayUnion() as described in the documentation. For example:
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});
The accepted answer used to be correct but is now wrong. Now there is an atomic append operation using the arrayUnion method:
https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
This is true as long as you are using firestore and not real time db (which I assume is the case from the tags)
I update 100's of documents every second by pushing new data to an array in its document. To get the document of which I am going to add data to, I use the mongoose .find().limit(1) function, and return the whole document. It works fine.
To help with some memory and cpu issues I have, I was wondering how I could get find() to only return the id of the document so I can use that to $push or $set new data.
Thanks.
You want to use Projection to tell your query exactly what you want off of your objects.
_id is always included unless you tell it not to.
readings = await collection
.find({
name: "Some name you want"
})
.project({
_id: 1 // By default
})
.toArray();
You could use the distinct method in order to get an array of _id for your query.
Follow this question
As mentioned by #alexmac, this works for me:
collection.find({}, '_id')
I have a Collection named "balance". I want to get the value of one document in the collection. In order to get only the latest element in the collection I use this query:
db.balance.find().sort({date: -1}).limit(1);
There's a column called 'value' and I want to get that.
db.balance.find().sort({date: -1}).limit(1).value; however does not show the data I want. It shows nothing:
What's wrong with it?
find returns a cursor. You'll need to convert it to an array in order to actually extract the value. Try this:
db.balance.find().sort({date: -1}).limit(1).toArray()[0].value;
This is, of course, much easier inside of meteor (either in code or via meteor shell) because you can do:
Balance.findOne({}, {sort: {date: -1}}).value;