How to allow only particular fields of a firestore document to be accessed publicly

Solution 1:

You can't. Security rules only work on a document-level basis, so you can't restrict read access to specific fields.

If you want to do something like you're suggesting, you'll probably need to restructure your data so that your non-public data is in a separate document. Most likely you'll want to do this by putting your private data in a subcollection. So you might end up with something like this...

collection: [
  document: {
    y: 'y'
    private-collection: [
      document: {
        x: 'x'
      }
    ]
  }
]

And then you'd set up your security rules like:

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{document} {
      allow read: if true;
      match /private-collection/{otherdoc} {
        allow read: if someOtherRuleThatYouAddHere();
      }
    }
  }
}