【问题标题】:How to efficiently match between arrays in a Mongo document and that in query criteria?如何有效地匹配 Mongo 文档中的数组和查询条件中的数组?
【发布时间】:2020-10-12 21:38:05
【问题描述】:

问题描述:

我想检索所有标记有字符串值数组的文档,如果其中一个字符串值包含在客户端传入的数组中。

代码:

发布架构:

const PostSchema = new mongoose.Schema(
  {
    post: {
      type: String,
      required: true,
      trim: true,
      maxlength: [3000, "A post should be less than 3000 characters"],
      unique: false,
    },
    details: {
      type: String,
      required: false,
      maxlength: [4000, "An author may add additional detail if they wish."],
    },
    tags: {
      type: [String],
      required: false,
    },
   ... 

示例发布文档:

  {
    "_id": "5d713995b721c3bb38c1f5d0",
    "user": "5c8a1d5b0190b214360dc031",
    "post": "The best composer of all time was Mozart",
    "details": "Some details here",
    "tags": ["music", "composers", "Mozart"],
  }

我愿意测试所有返回结果的解决方案。一个成功的解决方案是让查询返回所有 Post 文档,即使一个标签匹配搜索条件数组中的至少一个标签。

此外,从 Mongo DB 的角度来看,该解决方案应该是高效且低成本的,因为它可能是一个频繁的查询。

(在 SQL 中,此解决方案可能有多种变体,涉及在 Mongo 世界中执行不同操作的命令;虽然我可以在 SQL 中相当容易地做到这一点,但我想知道 Mongo 是否对此有同等直接的方法匹配。)

到目前为止,我已经尝试了各种方法并在此处查阅了官方 mongo 文档: https://docs.mongodb.com/manual/tutorial/query-arrays/

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    测试自己:https://mongoplayground.net/p/rwFf8oiQTqb

    使用find

    db.collection.find({tags: {$in: ["music", "movies"]}})
    

    使用aggregate

    db.collection.aggregate([
      {
        "$match": {
          "tags": {
            "$in": [
              "music",
              "movies"
            ]
          }
        }
      }
    ])
    

    结果:

    [
      {
        "_id": "5d713995b721c3bb38c1f5d0",
        "details": "Some details here",
        "post": "The best composer of all time was Mozart",
        "tags": [
          "music",
          "composers",
          "Mozart"
        ],
        "user": "5c8a1d5b0190b214360dc031"
      }
    ]
    

    【讨论】:

    • 这绝对有效;我想知道在频繁搜索中运行聚合的“成本”,但到目前为止,这似乎是最有效的解决方案。如果有的话,我也有兴趣查看其他方法。谢谢。
    • 不客气。我也更新了find 方法。
    猜你喜欢
    • 2017-07-21
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-31
    • 2015-12-15
    • 2016-07-27
    • 2016-05-05
    相关资源
    最近更新 更多