LoginSignup
2
3

More than 3 years have passed since last update.

FirestoreのCollectionに対してIN句を投げたい

Posted at

はじめに

CollectionからMySQLのIN句のように複数条件どれかに一致するDocumentを全て取得してくる方法について試してみたのでその内容の記事となります。

QueryについてはwhereFieldは割と使用しているのですが、複数条件に一致するDocument全て取得したい場合どうやるっけ?と気になり試してみた次第です!

使用ライブラリ

今回の検証ではPringを使用しております。
現在はdeprecatedとなっておりBallcap-iOSで行わなかったのは、なるべく早く動作確認したかったため使い慣れているという点でPringで検証しました。

データ作成

シンプルにnameのFieldをもつUserModelを定義してます。
このnameに対して複数条件どれかに一致するもの全てを取得してみようと思います。

@objcMembers
class User: Object {
    dynamic var name: String?
}

検証用のデータをFirestoreに保存

let userA: User = User(id: "1")
userA.name = "A"
userA.save()

let userB: User = User(id: "2")
userB.name = "B"
userB.save()


let userC: User = User(id: "3")
userC.name = "C"
userC.save()


let userD: User = User(id: "4")
userD.name = "D"
userD.save()

この段階でFirebaseのコンソール上でuserCollection以下に4つのDocumentが保存されていることが確認できます。
スクリーンショット 2019-05-08 0.13.06.png

 Firestoreに対しIN句をかける

let option: Options = Options()
option.predicate = NSPredicate(format: "name IN %@", ["A", "D"])
User.query.dataSource(options: option).get().onCompleted { (_, users) in
    for user in users {
        print("user:\(user)")
    }
}

以下XcodeのLog

user:User {
  id: 1
  createdAt: FIRTimestamp: seconds=1557242226 nanoseconds=587824821>
  updatedAt: FIRTimestamp: seconds=1557242226 nanoseconds=587824821>
  name: Optional("A")
}
user:User {
  id: 4
  createdAt: FIRTimestamp: seconds=1557242226 nanoseconds=592360973>
  updatedAt: FIRTimestamp: seconds=1557242226 nanoseconds=592360973>
  name: Optional("D")
}

参考

FirebaseFirestore Framework Document

NSPredicate

NSPredicate 全構文解説

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3