【问题标题】:Querying inside a subdocument array in mongodb在 mongodb 的子文档数组中查询
【发布时间】:2021-09-14 02:39:33
【问题描述】:

我对 MongoDB 或 NoSQL 数据库真的很陌生。 我有这个userSchema 架构

const postSchema = {
    title: String,
    posted_on: Date
}

const userSchema = {
    name: String,
    posts: [postSchema]
}

我想检索给定范围内用户的帖子(/api/users/:userId/posts?from=date&to=date&limit=limit)使用 mongodb 查询。在关系数据库中,我们通常创建两组不同的表并使用某些条件查询第二个表(帖子)并获得所需的结果。 我们如何在 mongodb 中实现相同的目标?我曾尝试通过引用this 来使用$elemMatch,但它似乎不起作用。

【问题讨论】:

  • 您可以添加您正在尝试执行的查询吗?同样$elemMatch 将返回一个匹配条件的数组元素

标签: javascript mongodb mongoose


【解决方案1】:

使用聚合框架实现此目的的两种方法,其功能远超查找功能。

使用find,我们主要从集合中选择文档,或者从项目中选择文档以保留所选文档中的某些字段,但在这里您只需要数组的一些成员,因此使用了聚合。

本地方式(文档级别的解决方案)不展开等

Test code here

查询

  • 过滤数组并只保留posted_on >1 和
  • 取数组的前 2 个元素(限制为 2)
db.collection.aggregate([
  {
    "$match": {
      "name": {
        "$eq": "n1"
      }
    }
  },
  {
    "$set": {
      "posts": {
        "$slice": [
          {
            "$filter": {
              "input": "$posts",
              "cond": {
                "$and": [
                  {
                    "$gt": [
                      "$$this.posted_on",
                      1
                    ]
                  },
                  {
                    "$lt": [
                      "$$this.posted_on",
                      5
                    ]
                  }
                ]
              }
            }
          },
          2
        ]
      }
    }
  }
])

Uwind 解决方案(集合级别的解决方案) (它更小一点,但保持本地化更好,但在你的情况下没关系)

Test code here

查询

  • 匹配用户
  • 展开数组,让每个成员都成为ROOT
  • 匹配日期>1
  • 限制2
db.collection.aggregate([
  {
    "$match": {
      "name": {
        "$eq": "n1"
      }
    }
  },
  {
    "$unwind": {
      "path": "$posts"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$posts"
    }
  },
  {
    "$match": {
      "$and": [
        {
          "posted_on": {
            "$gt": 1
          }
        },
        {
          "posted_on": {
            "$lt": 5
          }
        }
      ]
    }
  },
  {
    "$limit": 2
  }
])

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多