r4id4
r4id4

Reputation: 6077

Firestore query document based on comparison of 2 fields

Say I have this document

userProfile: {
  createdAt: '2018-01-01',
  updatedAt: '2018-01-04'
}

I want to retrieve all userProfiles that were updated after their creation, that means those that satisfy createdAt < updatedAt.
Can you do that in Firestore?

Something like this, but where the second operand is a field, not a value:

userProfileRef.where("createdAt", "<", "updatedAt")

Thanks

Upvotes: 0

Views: 674

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

You will not be able to do that with "standard" Firestore queries.

The easiest way would be to either:

  1. Have a default "dummy" date (e.g. 1900-01-01) in the updatedAt field if the doc was never updated after creation. You would then query with userProfileRef.where("updatedAt", ">", "1900-01-01")

or

  1. Have a specific flag in the document that you would update when you change the value of the updatedAt field (i.e. when you update the doc after creation).

Note that you cannot query for documents that don't contain a given field (watch this official video for more details), therefore you cannot rely on the absence of the updatedAt field.

Upvotes: 1

Related Questions