【问题标题】:Query array by stored index in document in MongoDB通过存储在 MongoDB 文档中的索引来查询数组
【发布时间】:2018-10-06 18:34:39
【问题描述】:

我有这样的文件

{
    "status": {
        "current": 0,
        "priority": [{
            "operationName": "PHOTO",
            "status": "WAITING"
        },
        {
            "operationName": "DESIGN",
            "status": "NOTARRIVED"
        },
        {
            "operationName": "COLOR_SEPARATION",
            "status": "NOTARRIVED"
        }]
    }
}

想查询这样的数据

{
    "status.priority.$status.current.operationName": {
        $in: ['SERVICES', 'PHOTO']
    }
}

当我这样查询时

{
    "status.priority.0.operationName": {
        $in: ['SERVICES', 'PHOTO']
    }
}

它返回所需的数据,因为'PHOTO' 是当前操作。

我需要根据数组的一个索引进行查询,这个索引存储在status.current的文档中

有什么提示吗?

更新 问题解决后,我想优化它。

【问题讨论】:

  • 请更具体地说明您想要实现的目标
  • 想要查询某个索引并且该索引存储在“$status.current”中的 db 中我想在我的查询中使用这个索引,例如 "status.priority.3.operationName"

标签: mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您可以在 3.6 中使用 $arrayElemAt$expr

类似

db.colname.find(
 {"$expr":{
   "$in":[
     {"$arrayElemAt":["$status.priority.operationName","$status.current"]},
     ['DESIGN', 'COLOR_SEPARATION', 'PHOTO']
   ]
 }}
)

【讨论】:

  • 如何使用索引来优化它?
【解决方案2】:

为此,您需要使用aggregation

db.collname.aggregate([{
    "$project": {
      "_id": 1,
      priority: { $arrayElemAt: ["$status.priority", '$status.current'] },
    }
  },
  {
    $match: {
      "priority.operationName": {
        $in: ['DESIGN', 'COLOR_SEPARATION', 'PHOTO']
      }

    }
  }
])

这对你有用。

结果会是这样的

{
    "_id" : ObjectId("5b6b656818883ec018d1542d"),
    "priority" : {
        "operationName" : "PHOTO",
        "status" : "WAITING"
    }
}

【讨论】:

  • 如何使用索引进行优化?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 2020-09-06
  • 2017-06-24
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
相关资源
最近更新 更多