📅  最后修改于: 2023-12-03 14:59:56.833000             🧑  作者: Mango
Cloud Firestore is a powerful NoSQL document database that is offered as a part of Google Firebase platform. It is designed to store and sync data for client- and server-side development, allowing for better real-time collaboration, data synchronization, and offline support.
Developers can use Cloud Firestore in a variety of ways, from mobile and web apps to connected devices and serverless applications. Its advanced querying and indexing capabilities help developers to quickly and easily retrieve useful data from their databases.
To start using Cloud Firestore, you need to:
Sign up for a Firebase account and enable Cloud Firestore in your project.
Install the Cloud Firestore library in your programming language of choice.
Begin creating databases, collections, and documents.
Here is an example in Dart, a programming language for building mobile, desktop, and server applications:
import 'package:cloud_firestore/cloud_firestore.dart';
final firestoreInstance = FirebaseFirestore.instance;
Future<void> addUser() {
// Add a new document to the "users" collection
return firestoreInstance.collection("users")
.doc("XWx5QScx4C1YdSZ7V")
.set({
"name": "John Doe",
"age": 25,
"email": "johndoe@gmail.com"
})
.then((value) => print("User Added"))
.catchError((error) => print("Failed to add user: $error"));
}
In this example, we are adding a new user document with a specific ID to the "users" collection. We can retrieve this document later by using a reference to its ID:
Future<void> getUser() async {
// Get a document from the "users" collection
DocumentSnapshot userSnapshot = await firestoreInstance
.collection("users")
.doc("XWx5QScx4C1YdSZ7V")
.get();
if (userSnapshot.exists) {
Map<String, dynamic> userData = userSnapshot.data();
print("User: ${userData['name']}, Age: ${userData['age']}, Email: ${userData['email']}");
} else {
print("User not found");
}
}
One of the key benefits of Cloud Firestore is its advanced querying capabilities. For example, you can filter documents by field values, perform range queries, and sort the results:
Future<void> queryUsers() async {
// Query the "users" collection for all users over the age of 21
QuerySnapshot usersSnapshot = await firestoreInstance
.collection("users")
.where("age", isGreaterThanOrEqualTo: 21)
.get();
if (usersSnapshot.docs.isNotEmpty) {
for (var user in usersSnapshot.docs) {
Map<String, dynamic> userData = user.data();
print("User: ${userData['name']}, Age: ${userData['age']}, Email: ${userData['email']}");
}
} else {
print("No users found");
}
}
Cloud Firestore is a powerful, scalable, and flexible document database that offers real-time synchronization, offline data support, and advanced querying capabilities. With its easy-to-use API and extensive documentation, it is easy for developers to get started and build robust applications on the Firebase platform.