날짜 범위별 Firestore 쿼리
날짜 범위가 긴 컬렉션을 쿼리하려면 도움이 필요합니다.아래 예제 문서를 참조하십시오.날짜 범위를 사용하여 startTime 필드를 쿼리합니다.

제가 가지고 있기 때문에.dueDateCloud Firestore에 "타임스탬프"(문자열이나 숫자가 아님)로 저장된 필드에서 2017년까지 제출해야 하는 송장 문서를 받기 위해 이 작업을 수행했습니다.
let start = new Date('2017-01-01');
let end = new Date('2018-01-01');
this.afs.collection('invoices', ref => ref
.where('dueDate', '>', start)
.where('dueDate', '<', end)
);
참고: dueDate필드가 Date() 객체와 함께 소방서에 저장되었습니다. 예: this.doc.dueDate = new Date('2017-12-25')
datetime 개체를 Unix 시간(1970년 1월 1일 이후 초)으로 저장할 수 있습니다.그런 다음 다음 다음과 같이 where select를 사용할 수 있습니다.
collectionRef.where("startTime", ">=", "1506816000").where("startTime", "<=", "1507593600")
Btw - 앱에서 날짜/시간에서 유닉스 시간으로 변환하려면 우수한(현재는 사용되지 않는) 라이브러리 모멘트를 사용할 수 있습니다(Js 또는 노드로 무언가를 구축하는 경우).
var startfulldate = admin.firestore.Timestamp.fromDate(new Date(1556062581000));
db.collection('mycollection')
.where('start_time', '<=', startfulldate)
.get()
.then(snapshot => {
var jsonvalue: any[] = [];
snapshot.forEach(docs => {
jsonvalue.push(docs.data())
})
res.send(jsonvalue);
return;
}).catch( error => {
res.status(500).send(error)
});
const event = new Date();
const expirationDate = admin.firestore.Timestamp.fromDate(event);
const query = collectionRef.where('startTime', '<=', expirationDate)
~하듯이startTime로 저장된.Timestamp이 쿼리 범위는 보다 정확하게 수행할 수 있습니다(이는 긴 날짜 범위 또는 동일한 날짜 범위의 조건 모두에 적합함).
const start = new Date('2021-01-01T00:00:00.000z');
const end = new Date('2021-03-01T23:59:59.000z');
db.collection('Data').where('startTime', '>=', start).where('startTime', '<=', end).get().then(data => {
//pass your 'data' here
});
저는 이것을 제 Node.js 앱에서 사용했습니다.이것이 유용하기를 바랍니다.
최근 Firebase Firestore를 사용하는 모든 사용자는 Firebase 구현 설정(Firebase 버전에 따라 다름)에 따라 다릅니다.
이전에는 Firestore가 저장하고 있었습니다.Timestamp로서Date하지만 여기 문서에 설명된 바와 같이 그것은 곧 a로 대체될 것입니다.Timestamp물건.여기에서 타임스탬프 문서를 참조하십시오.
다음 예제와 같이 Firebase에서 Date 대신 Timestamp 개체를 사용하도록 강제하는 설정을 코드에 추가하여 이미 구현을 강제할 수 있습니다.
var firebaseApp = firebase.initializeApp({
apiKey: [APIKEY],
authDomain: [FIREBASEAPPDOMAIN],
projectId: [PROJECTID]
});
var firestore = firebase.firestore();
var settings = { timestampsInSnapshots: true }; // force Timestamp instead of Date
firestore.settings(settings);
해결책은 Date.now()를 사용하는 것입니다.Firebase의 타임스탬프 서비스 사용을 중지합니다. 예를 들어, 1514271367000과 같이 시간의 숫자 값으로 작업해야 합니다. Firestore에서 26/12/2017 1:56:07 GMT- 0500(-05)을 사용하면 작동하지 않습니다.쿼리의 예는 다음과 같습니다.
this.fsService.afs.collection('chats/4bY1ZpOr1TPq8bFQ3bjS/finance/123+finance/12345'
, ref => ref.orderBy('hour').startAt(1514184967000).endAt(1514271367000))
.valueChanges().subscribe(data =>{
this.mensajes = data;
})
저처럼 PHP를 사용하여 Firestore에 액세스하는 사람들은 다음과 같은 작업을 수행할 수 있습니다.
$startTime = new DateTime('2020-05-23 00:00:00');
$endTime = new DateTime('2020-06-23 23:59:59');
$start = new Google\Cloud\Core\Timestamp($startTime);
$end = new Google\Cloud\Core\Timestamp($endTime);
// fb is a Google\Cloud\Firestore\FirestoreClient object
$this->query = $this->fb->collection('your_collection');
$aux = $this->query;
$aux = $aux->where('startTime', '<', $end);
$aux = $aux->where('startTime', '>', $start);
return $aux->documents();
즐거운 시간 되세요.
특정 필드의 날짜 범위별로 컬렉션에서 문서를 찾는 일반 기능:
public List<QueryDocumentSnapshot> findDocsByDateRange(
String collection,
String fieldStartDate,
String fieldEndDate,
Date startDate,
Date endDate) {
ApiFuture<QuerySnapshot> querySnapshot = fireStore()
.collection(collection)
.whereGreaterThanOrEqualTo(FieldPath.of(fieldStartDate), startDate)
.whereLessThanOrEqualTo(FieldPath.of(fieldEndDate), endDate)
.get();
return querySnapshot.get().getDocuments();
}
패키지:
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.FieldPath;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.QueryDocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
프런트엔드 응용프로그램에서 Firebase 타임스탬프 및 날짜를 사용하여 문서를 쿼리하고 저장할 수 있는 방법은 다음과 같습니다.

이게 도움이 될 거라 생각합니다
yourMethod() {
var date = DateTime.now();//
print("First Date > " + DateTime(date.year, date.month, 1).toString());
var datex = new DateTime(date.year, date.month + 1, 0);
print("Last Date > " +datex);//
//
Firestore.instance
.collection('biling')
.where("driverId", isEqualTo: widget.uid)
.where("date",
isGreaterThanOrEqualTo:
new DateTime(date.year, date.month, 1).toString())//1
.where("date", isLessThanOrEqualTo: datex.toString())//2
.orderBy('date', descending: true)
.getDocuments()
.then(
(QuerySnapshot snapshot) => {
snapshot.documents.forEach((f) {
if (this.mounted) {
setState(() {
totalP += double.tryParse(f.data["price"]);
});
}
print("_price " + f.data["price"]);
print("_duePaymntForCompay " + f.data["duePaymntForCompay"]);
}),
},
);
}
.where가 나에게 작동하지 않기 때문에 이제 당신은 조건이 있는 문서를 필터링하기 위해 이러한 쿼리를 사용해야 합니다.
db.collection("id").whereGreaterThan("field","value")
.whereEqualTo("field","value")
.whereLessThen("field","value")
Moment JS로 날짜를 포맷하고 일, 월, 년으로 분할했습니다.
const currentDate = moment().format("DD-MM-YYYY").split("-");
const currentDay = currentDate[0];
const currentMonth = currentDate[1];
const currentYear = currentDate[2];
const allDocuments = await collectionRef
.doc(docId)
.collection(*COLLECTION NAME*)
.where(
*DATE PARAMETER NAME*,
">=",
new Date(`${currentYear}-${currentMonth}-${currentDay}`)
)
.where(
*DATE PARAMETER NAME*,
"<",
// ${parseInt(currentDay) + *Number of days you want in range*}
new Date(`${currentYear}-${currentMonth}-${parseInt(currentDay) + 1}`)
)
.get();
언급URL : https://stackoverflow.com/questions/47000854/firestore-query-by-date-range
'programing' 카테고리의 다른 글
| Git'fatal:새 인덱스 파일을 쓸 수 없습니다.' (0) | 2023.07.04 |
|---|---|
| 같은 도메인을 사용하여 NGINX 서버에서 장고와 워드프레스를 실행하는 방법은 무엇입니까? (0) | 2023.07.04 |
| 기존 디렉토리 구조에 보관 압축 풀기 (0) | 2023.07.04 |
| Mac에서 Git 구성 파일을 찾는 방법 (0) | 2023.07.04 |
| 완성도를 사용하지 않는 홈브루의 기트 (0) | 2023.07.04 |
