Multi-document Upsert

I’m trying to upsert an array of ~1000 documents to Fauna on a daily basis. I’ve written my query in FQL, where I match the new array with the existing collection based on the URL param, but for some reason, even if another document with that URL exists in my collection, the document still gets created.

var arrData = [
  {
    data: {
  url: "https://www.example.com/in/nameOne/",
  firstName: "First",
  lastName: "Last",
}
  },
  {
    data: {
  url: "https://www.example.com/in/nameTwo/",
  firstName: "First",
  lastName: "Last",
}
  }
]

q.Map(arrData, q.Lambda(['d'], 
  q.If(
      q.Exists(
        q.Match(q.Index('zap'), q.Select(['data', 'url'], q.Var('d')))
      ),
      q.Replace(
        q.Select(
          'ref',
          q.Get(
            q.Match(q.Index('zap'), q.Select(['data', 'url'], q.Var('d')))
          )
        ),
        Var('d')
      ),
      q.Create(q.Collection('users'), q.Var('d'))
    )
))

@lb_ne Welcome to the Fauna Forums!!

Can you share the definition for Index zap ?

Hi Jay, it’s just an index that lists all the collection’s documents. Does that make sense?

You cannot use the Index without Terms because Exist(Match(Index())) fails.

Here is an example.
Below Index has no Terms and gives all documents in login collection.

Get(Index("all_login"))

{
  ref: Index("all_login"),
  ts: 1604004141590000,
  active: true,
  serialized: true,
  name: "all_login",
  source: Collection("login"),
  partitions: 8
}
Exists(Match(Index("all_login")))

true

But if you pass Terms to this even though it is not expecting, Exists returns false.

Exists(Match(Index("all_login"), "123"))

false

Based on your match statement, you want to check if there is a document with the url already, so your index should have url as Terms.

Hope this helps.