0

I need to find all document IDs with name: "Nick", so I can update the score.


I have the following Firestore Database structure:

{
  "c4ca4238a0b923820dcc509a6f75849b": {
    title: "Tiger",
    user: {
      name: "Chris",
      score: 1
    }
  },
  "c81e728d9d4c2f636f067f89cc14862c": {
    title: "Lion",
    user: {
      name: "Nick",
      score: 2
    }
  }
}

From the documentation I see that I can find documents using where like this:

const dbQuery = query(collection(dbFirestore, "posts"), where("title", "==", "Tiger"));

const dbSnapshot = await getDocs(dbQuery);

dbSnapshot.forEach((result) => {
  console.log(result.id, " => ", result.data());
});

But I don't see anything about how to search by a child element (user.name)?

1 Answers1

0

Firestore is a NoSQL database which inherits how you query on any other NoSQL database. To specify a query condition on fields in an embedded/nested document, use dot notation "field.nestedField". When querying using dot notation, the field and nested field must be inside quotation marks.

You could get all the documents from nested objects by using this sample query:

const dbQuery = query(collection(db, "posts"), where("user.name", "==", "Nick"));

const dbSnapshot = await getDocs(dbQuery);

dbSnapshot.forEach((result) => {
  console.log(result.id, " => ", result.data());
});
Marc Anthony B
  • 3,635
  • 2
  • 4
  • 19
  • `where("user.name", "==", "Nick")` is way simplier than I thought it would be, lol! Thank you so much for your help! –  May 11 '22 at 06:10