您好,我有 2 个数组,例如 电话号码[1,2,3] 金额[10,20,30] 我需要将数据存储在单个文档中,例如 字段 1: 1 字段 2: 10
The code I tried is
我把对象当作 **
public class Pojo {
String invitee;
Map<Integer,Integer>phoneAmount;
public Pojo(String invitee, Map<Integer, Integer> phoneAmount)
{
this.invitee = invitee;
this.phoneAmount=phoneAmount;
}
}**
在另一个类(class)
Map<int[], int[]> phoneAmount = new HashMap<>();
phoneAmount.put(phonenumber,amount);
db.collection("Split").document("invitees").set(phoneAmount).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
它显示错误 java.lang.RuntimeException:无法序列化对象。不支持具有非字符串键的映射 在 com.google.android.gms.internal.zzejw.zza(未知来源) 在 com.google.android.gms.internal.zzejw.zza(未知来源) 在 com.google.android.gms.internal.zzejw.zzbp(未知来源)
最佳答案
Although Cloud Firestore can store arrays, it does not support querying array members or updating single array elements.
我个人不推荐使用这种方法。 Firebase 还建议不要使用数组的众多原因之一是它使安全规则无法编写。
但是,您仍然可以利用 Cloud Firestore 的其他功能对此类数据建模。
让我们举个例子。假设您有一个如下所示的数据库:
{
title: "My Book",
categories: [
"science",
"computer science",
"technology"
]
}
您需要知道,如果要查询属于“科学”类别的所有书籍
,使用此数据结构是无法执行此查询的。
要解决这个问题,您可以考虑另一种数据结构,其中每个类别都是映射中的键,所有值都是 true
。
{
title: "My Book",
categories: {
"science": true,
"computer science": true,
"technology": true
}
}
要查询您的数据库,您可以使用此查询:
db.collection("books")
.whereEqualTo("categories.science", true)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {/* ... */});
对于您的特定情况,您可以使用如下所示的数据库结构:
{
title: "phonenumber",
categories: {
"12345": true,
"67890": true,
"43215": true
}
}
查询请使用以下代码:
db.collection("phonenumbers")
.whereEqualTo("categories.12345", true)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {/* ... */});
2018 年 8 月 13 日编辑:
根据有关 array membership 的更新文档,现在可以使用 whereArrayContains()
方法根据数组值过滤数据。一个简单的例子是:
CollectionReference citiesRef = db.collection("cities");
citiesRef.whereArrayContains("regions", "west_coast");
This query returns every city document where the regions field is an array that contains west_coast. If the array has multiple instances of the value you query on, the document is included in the results only once.
关于android - 将数组存储到对象数据类型到 android 和 iOS 中的 firestore(swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759401/