【问题标题】:MongoDB query to find property of first element of arrayMongoDB查询以查找数组第一个元素的属性
【发布时间】:2013-10-11 01:52:52
【问题描述】:

我在 MongoDB 中有以下数据(根据我的问题进行了简化)。

{
    _id: 0,
    actions: [
        {
            type: "insert",
            data: "abc, quite possibly very very large"
        }
    ]
}
{
    _id: 1,
    actions: [
        {
            type: "update",
            data: "def"
        },{
            type: "delete",
            data: "ghi"
        }
    ]
}

我想要为每个文档找到第一个动作类型,例如

{_id:0, first_action_type:"insert"}
{_id:1, first_action_type:"update"}

(如果数据结构不同也没关系,但我需要以某种方式存在这些值。)

编辑:我尝试过db.collection.find({}, {'actions.action_type':1}),但显然它返回了actions数组的所有元素。

NoSQL 对我来说很陌生。以前,我会将所有这些存储在关系数据库中的两个表中,然后执行SELECT id, (SELECT type FROM action WHERE document_id = d.id ORDER BY seq LIMIT 1) action_type FROM document d 之类的操作。

【问题讨论】:

  • 只需...actions[0] 为collection.find method
  • 这些文件很大...我希望使用投影或其他东西来帮助我只获得我需要的东西。
  • 你可以添加索引
  • 在这样的 SO 问题中,您应该包含一个尝试过的解决方案,在这种情况下是您尝试过的查询,但没有成功。

标签: mongodb


【解决方案1】:

您可以在投影中使用$slice 运算符。 (但对于你所做的,我不确定当你更新它时数组的顺序是否保持不变。请记住))

db.collection.find({},{'actions':{$slice:1},'actions.type':1})

【讨论】:

    【解决方案2】:

    您也可以使用2.2版本中引入的Aggregation Pipeline:

    db.collection.aggregate([
      { $unwind: '$actions' },
      { $group: { _id: "$_id", first_action_type: { $first: "$actions.type" } } }
    ])
    

    【讨论】:

    • 它将返回整个数组,需要在组之前展开。像这样: db.collection.aggregate([ { $unwind: '$actions' }, { $group: { _id: "$_id", first_action_type: { $first: "$actions.type"} } } ])
    • @PaulDraper 抱歉打错了。已修复,您可以立即尝试 :)
    【解决方案3】:

    使用$arrayElemAt 操作符实际上是最优雅的方式,虽然语法可能不直观:

    db.collection.aggregate([
      { $project: {first_action_type: {$arrayElemAt: ["$actions.type", 0]}
    ])
    

    【讨论】:

      猜你喜欢
      • 2013-04-30
      • 1970-01-01
      • 2015-12-17
      • 2020-02-29
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多