简体   繁体   English

使用 ReactiveMongoDB 更新文档时使用数组过滤器

[英]Using array filters when updating a document with ReactiveMongoDB

Is there a way to use MongoDB's identifier update array filter in ReactiveMongoDB (19.2)?有没有办法在 ReactiveMongoDB (19.2) 中使用 MongoDB 的标识符更新数组过滤器 Imagine a db collection schema of:想象一个数据库集合模式:

{
    "_id": ObjectId("617942b33b850d6bbc490420"),
    "provider": "Google",
    "myArr_e": [
        {
            "name": "cloud",
            "lastDate": ISODate("2021-10-27T18:00:00.000+00:00")
        }
    ]
}

I want to update lastDate field where the document id is ObjectId("617942b33b850d6bbc490420") and the myArr_e.name is "cloud".我想更新lastDate字段,其中文档 ID 为ObjectId("617942b33b850d6bbc490420")并且myArr_e.name为“cloud”。 I can successfully compose the query in MongoDB with the following:我可以使用以下内容在 MongoDB 中成功编写查询:

db.apv.updateOne({ "_id": ObjectId("617942b33b850d6bbc490420") }, { $set: { "myArr_e.$[elem].lastDate": new Date() }}, { "arrayFilters": [{ "elem.name": "cloud" }]});

But I cannot do this in my app with ReactiveMongoDB.但是我无法在我的应用程序中使用 ReactiveMongoDB 执行此操作。 This was my best attempt:这是我最好的尝试:

  def getCollection(collName: String): Future[JSONCollection]

  def updateMyArr: Future[WriteResult] = {

    val q = obj("_id" -> obj("$oid" -> "617942b33b850d6bbc490420"))
    val u = obj("$set" -> obj("myArr_e.$[elem].lastDate" -> new Date()))
    val af = obj("arrayFilters" -> arr(obj("elem.name" -> "cloud")))

    for {
      coll <- getCollection("collName")
      uwr <- coll.update.one(q, u, upsert = false, multi = false, collation = None, arrayFilters = af)
    } yield {
      uwr
    }

  }

I'm getting a http 202 from this but I can see that the document hasn't updated.我从中获得了一个 http 202,但我可以看到该文档尚未更新。 Is this possible in ReactiveMongoDB (19.2)?这在 ReactiveMongoDB (19.2) 中可能吗? I've tried to find documentation on this but if it's out there then it's hiding from me.我试图找到关于此的文档,但如果它在那里,那么它就会对我隐藏。 With thanks_谢谢_

This is actually editing the document correctly this morning so this must have been me but I wanted to leave it up in case anyone is looking for an example of how to do this.这实际上是今天早上正确编辑文档,所以这一定是我,但我想留下它,以防有人正在寻找如何执行此操作的示例。 Also just a slight amendment to ensure an ISODate type is written to the field rather than a Long type & per the documentation the smartest way to construct the update object:也只是稍作修改,以确保将ISODate类型写入字段而不是Long类型,并且根据文档是构建更新对象的最ISODate方法:

val u = obj("$currentDate" -> obj("myArr_e.$[elem].lastDate" -> true))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM