ウェブサイト検索

javascript - 日付範囲による Firestore クエリ


日付範囲で長いコレクションをクエリするためのヘルプが必要です。以下の例のドキュメントを参照してください。日付範囲を使って startTime フィールドをクエリしたいです。

回答 #1

Cloud FirestoreにdueDateフィールドを「timestamp」として保存している(stringやnumberとしてではなく)ので、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() オブジェクトとして Firebase に保存されました。例:this.doc.dueDate=new Date('2017-12-25')

回答 #2

datetimeオブジェクトをUnix時間(1970年1月1日からの秒数)として保存することができます。そうすれば、次のようにwhere句を使うことができます。

collectionRef.where("startTime", ">=", "1506816000").where("startTime", "<=", "1507593600")

ちなみに、アプリでdatetimeをUnix時間に変換するには、素晴らしい(現在は非推奨の)ライブラリmomentを使うことができます(もしjsやnodeで何かを作っている場合)。

回答 #3

Firestore特有のTimestampクラスを使用してクエリを実行できます。

以下の例を見てください:

    const startfulldate = admin.firestore.Timestamp.fromDate(
       new Date(1556062581000)
    );

    const snapshot = await db.collection('mycollection')
      .where('start_time', '<=', startfulldate)
      .get();

回答 #4

const event = new Date();
const expirationDate = admin.firestore.Timestamp.fromDate(event);
const query = collectionRef.where('startTime', '<=', expirationDate)

回答 #5

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のアプリで使いました。役に立つことを願っています。

関連記事