This question already has answers here:
How to use array-contains operator with an array of objects in Firestore?
(2 answers)
Firestore to query by an array's field value
(3 answers)
Query firestore array of objects
(2 answers)
Closed last month.
After reading a bunch of threads regarding trying to perform queries on fields with dynamic keys in a document, I have two questions.
Is it possible to perform the following "query" on my data model: "Get field where createdDate is equal or greater than todays date"?
Should I change the data model?
I have documents (test.com in the below image) that have fields where the key is dynamic (0, 1, 2, 3 and so on). Each field is a "map", which (correct me if Im wrong) contains an object. Each object have a "createdAt". I want to query all fields on "createdAt" and return all fields where "createdAt" is equal to or greater than todays date. So in my image, as of today it is the 12 of january, the field with the key "1" should be returned.
My query below doesn't work due to I don't "reach down to each field", would each document have just color, createdAt and domainName flattened It would have worked.
const domainsQuery = query(
collectionGroup(db, "domains"),
where("releaseAt", ">=", new Date())
);
It's not possible to fetch only some fields of a document in firebase. You always fetch all fields of a document. You can filter returned documents but not the fields of documents. You should probably adjust your model.
I recommend just creating an additional subcollection (name can be arbitrary) and making those dynamic keys into ids of subdocuments instead.
Is it possible to perform the following "query" on my data model: "Get field where createdDate is equal or greater than today's date"?
No, there is not. You cannot filter documents based on a single field property that exists inside an object, which is contained in an array. What you are looking for cannot be achieved using partial data.
If you need to filter based only on a particular field, then you should consider duplicating the data on which you want to perform the filtering and adding it to a separate array. In this way, you can query the collection using the array-contains operator.
Should I change the data model?
A possible solution would be to get all those objects out of the array and add them as separate documents inside a sub-collection. In that way, you can simply perform the desired query.
Related
So basically I have an object schema that has an array field that will hold ids for objects inside a different collection. This array field has the potential to have thousands of ids inside of it. I have been omitting this field using .select(["-fieldName"]); in my queries up till now but I need to include it in my query if I wanna add on to it.
I would assume querying an object with such a large field is costly in performance so therefore my question is how can I efficiently query such an object?
I would like to just omit this field in my query but then I can't add ids into it.
If you just want to add an item to the array field you can use the $push operator.
collection.updateOne(query, { $push: { arrayField: value } });
I would like to update the completed property of an object in an array in Firestore, but I have no idea how to reach that specific element in the array. The image will show the structure.
I have come up this far but don't know how to choose, for example, item 1 in the array. I was thinking of using its ID (it has an id property) but don't know how to get there.
const businessRef = db.collection('approvedBusinesses').doc(businessId)
try {
businessRef.update({
[`bookings.${currentDate} ????? `]: true // what to add after currentDate?
})
By the way, this is how the array was created (and how other objects are pushed to it)
const bookingObj = {
carro: 'PASSA_CARRO',
completed: false,
userId: userObject.uid,
}
businessRef.update({
[`bookings.${currentDate}`]: firebase.firestore.FieldValue.arrayUnion(bookingObj),
})
Firestore does not have an operation that allows you to update an existing item in an array by its index.
To update an existing item in the array, you will need to:
Read the entire document into your application.
Modify the item in the array in your application code.
Write back the entire array to the document.
I'm pretty sure this has been asked before, so let me see if there's an answer with an example.
Also see:
How to remove an array element according to an especific key number?
Simple task list ordering - how to save it to Firebase Firestore?
How to update only a single value in an array
How to update an "array of objects" with Firestore?
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 am currently trying to filter an object via POST from a form the form is made of checkboxes and as a result I need to be able to search an array of objects for multiple values on the same key.
My POST looks similar to this,
{
tax_year: ['2016/17', '2017/18'],
status : ['completed'],
user : [1,4,78]
}
How would I go about search an array of objects and returning all the objects that have a matching key and value? I know I can do a single find with underscore like so,
var result = _.where(historyData, {tax_year: "2016/17"});
but I have no clue as to how to search for multiple matching keys and values?
It seems that you're matching on both of the values in an array value (regardless of whether there are more array values or not). If that's true, you might have to use the _.filter() method, where you can provide whatever logic you need in the 'predicate'. Alternatively, you could add a unique identifier on the server side to each record and match on that.
Is there any methods or packages, that can help me add auto increments to existing collection? Internet full of information, about how to add AI before you create collection, but I did not find information on how to add AI when collection already exist...
MongoDB does not have an inbuilt auto-increment functionality.
Create a new collection to keep track of the last sequence value used for insertion:
db.createCollection("counter")
It will hold only one record as:
db.counter.insert({_id:"mySequence",seq_val:0})
Create a JavaScript function as:
function getNextSequenceVal(seq_id){
// find record with id seq_id and update the seq_val by +1
var sequenceDoc = db.counter.findAndModify({
query:{_id: seq_id},
update: {$inc:{seq_val:1}},
new:true
});
return sequenceDoc.seq_val;
}
To update all the already existing values in your existing collection, this should work (For the empty {}, you can place your conditions if you want to update some documents only):
db.myCollection.update({},
{$set:{'_id':getNextSequenceVal("mySequence")}},{multi:true})
Now you can insert new records into your existing collection as:
db.myCollection.insert({
"_id":getNextSequenceVal("mySequence"),
"name":"ABC"
})
MongoDB reserves the _id field in the top level of all documents as a primary key. _id must be unique, and always has an index with a unique constraint. It is an auto-incrementing field. However, it is possible to define your own auto-incrementing field following the tutorial in the MongoDB documentation.
Tutorial link: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/