Firestore - 如何执行“where in”查询?

23 浏览
0 Comments

Firestore - 如何执行“where in”查询?

我想知道是否有可能在一次网络请求中通过一个ID列表获取多个文档的数据。

0
0 Comments

Firestore中的"where in"查询是指根据指定的一组值来查询数据。下面的代码演示了如何在Firestore中执行"where in"查询:

async getUsers({userIds}) {
    const refs = userIds.map(id => this.firestore.doc(`users/${id}`))
    const users = await this.firestore.getAll(...refs)
    console.log(users.map(doc => doc.data()))
}

或者使用Promise语法:

getUsers({userIds}) {
    const refs = userIds.map(id => this.firestore.doc(`users/${id}`))
    this.firestore.getAll(...refs).then(users => console.log(users.map(doc => doc.data())))
}

这种方法允许查询超过10个ID,因此应该是首选的解决方案。需要注意的是,这种方法可能只适用于特定的Firebase版本,比如Node,而不适用于JavaScript API。

然而,需要注意的是,在Firestore的官方文档中并没有明确提供关于`getAll`方法的文档,因此可能需要自己尝试或者查阅其他资源来了解更多关于该方法的信息。

0
0 Comments

Firestore - 如何执行“where in”查询?

在Node.js中,您可以使用firestore.getAll()方法来执行多个文档的查询。您需要传递一个包含文档引用的数组作为参数。以下是一个示例代码:

let documentRef1 = firestore.doc('col/doc1');
let documentRef2 = firestore.doc('col/doc2');
firestore.getAll(documentRef1, documentRef2).then(docs => {
  console.log(`First document: ${JSON.stringify(docs[0])}`);
  console.log(`Second document: ${JSON.stringify(docs[1])}`);
});

这个方法是适用于服务器端SDK的。

最近,Firestore发布了一个更新,支持“in”查询。您可以使用where语句和FieldPath.documentId()来执行“where in”查询。以下是一个示例代码:

myCollection.where(firestore.FieldPath.documentId(), 'in', ["123","456","789"])

如果您想使用动态生成的文档引用数组来执行查询,可以这样做:

firestore.getAll(...arrayOfReferences).then()

您可以通过以下链接查看更多关于这个更新的信息:Cloud Firestore Now Supports IN Queries!

如果您在使用angularfire或firebase vanilla libs时遇到问题,可以尝试使用以下代码:

firestore.getAll.call(null, arrayOfReferences)

请注意,目前“in”过滤器最多只支持10个项目,超过这个数量可能会变得无用。

在Android中,您可以通过以下代码执行“where in”查询:

List lst;
FirebaseFirestore.getInstance().collection("collection_name").whereIn(FieldPath.documentId(), lst).get().addOnCompleteListener(...);

在Python SDK中,您需要导入`firestore_v1`模块,并使用`firestore_v1.field_path.FieldPath.document_id()`或`__name__`来执行查询。

希望这些信息对您有所帮助!

0
0 Comments

文章标题:Firestore - 如何执行“where in”查询?

在最新的功能发布中,他们宣布了这个功能的实现,你可以点击这里查看:https://firebase.googleblog.com/2019/11/cloud-firestore-now-supports-in-queries.html

现在你可以使用类似下面的查询语句,但是需要注意输入的大小不能超过10个:

userCollection.where('uid', 'in', ["1231","222","2131"])

他们提供了一个whereIn查询,而不是where查询。但是我不知道如何根据特定集合中的文档ID列表设计查询语句。请帮忙解答。

你可以尝试使用下面的代码:

db.collection('users').where(firebase.firestore.FieldPath.documentId(), 'in',["123","345","111"]).get()

非常感谢,特别是对于firebase.firestore.FieldPath.documentId()的使用。

如果输入数组大于10个,我应该使用什么方法呢?

你可以使用Promise.all()方法(参考链接:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)。

以上就是关于Firestore如何执行“where in”查询的问题以及解决方法的整理。

0