0

Lets say I have 100 documents with fields

Name Age Address

Now suppose my business model is change and I want to add new field call PhoneNumber.

How to add field PhoneNumber in all 100 documents ? Is is possible to such stuff on NoSQL database?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Sujin Shrestha
  • 1,203
  • 2
  • 13
  • 23

2 Answers2

0

You will have to write code to iterate all the documents to update, then actually update a new value in each one of them. Firestore has no similar command as "update tablename set x=y where ..." in SQL.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

Is is possible to such stuff on NoSQL database?

Yes it is! Assuming you have a User model class that look like this:

public class User {
    private String name;
    private int age;
    private String address;
    private String phoneNumber; //Property that is newly added

    public User() {}

    public User(String name, int age, String address, String phoneNumber) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.phoneNumber = phoneNumber;
    }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }

    public String getAddress() { return address; }
    public void setAddress(String address) { this.address = address; }

    public String getPhoneNumber() { return phoneNumber; }
    public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }
}

To actually add a new property and update it accordingly, you need to use setters. If you are setting the values directly onto the public fields, the setters are not mandatory.

How to add field PhoneNumber in all 100 documents?

As also @Doug Stevenson mentioned in his answer, to solve this, you need to iterate all the documents within your users collection. So please use the following lines of code:

db.collection("users").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                User user = document.toObject(User.class);
                user.setPhoneNumber("+1-111-111-111"); //Use the setter
                String id = document.getId();
                db.collection("users").document(id).set(user); //Set user object
            }
        }
    }
});

The result of this code would be to add the phoneNumber property to all you User objects with a default value of +1-111-111-111. You can also set the value to null if it's more convenient for you. At the end, the updated object is set right on the corresponding reference.

If you are not using a model class, please see my answer from this post.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193