查询复杂文档,如MongoDB中的矩阵

时间:2014-10-30 12:59:11

标签: mongodb mongoose mongodb-query

某些文档具有以下架构。文档结构类似于Matrix。矩阵的每个元素都是键值对{k:1, v:".."}。行中的某些元素可能不存在。

{
  doc: {
    matrix: [
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:"foo"}, {k:4; v:".."}, {k:5; v:".."}, {k:6; v:".."}, {k:7; v:".."}],
     [{k:1; v:".."}, {k:5; v:".."}, {k:6; v:".."}],
     [{k:2; v:".."}, {k:3; v:".."}, {k:4; v:".."}, {k:7; v:".."}],
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:"foo"}, {k:6; v:".."}, {k:7; v:".."}],
     [{k:6; v:".."}, {k:7; v:".."}],
     [{k:3; v:".."}, {k:4; v:".."}, {k:5; v:".."}, {k:6; v:".."}],
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:"foo"}, {k:4; v:".."}, {k:5; v:".."}, {k:6; v:".."}, {k:7; v:".."}],
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:".."}, {k:4; v:".."}, {k:5; v:".."}, {k:6; v:".."}, {k:7; v:".."}],
     [{k:6; v:".."}, {k:7; v:".."}],
     [{k:7; v:".."}]
    ]
  }
}

在上面的文档中,矩阵的第一行包含所有7个元素。第二行只有3个元素。等等。

有没有简单的方法让行包含key = 3和value =" foo"?

输出应为:

{
  doc: {
    matrix: [
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:"foo"}, {k:4; v:".."}, {k:5; v:".."}, {k:6; v:".."}, {k:7; v:".."}]
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:"foo"}, {k:6; v:".."}, {k:7; v:".."}],
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:"foo"}, {k:4; v:".."}, {k:5; v:".."}, {k:6; v:".."}, {k:7; v:".."}]
    ]
  }
}

1 个答案:

答案 0 :(得分:1)

我不熟悉mongoose,但在mongodb shell中,可以使用aggregation来实现以下输出:

> db.collectionName.aggregate({$unwind: "$doc.matrix"}, {$match: {"doc.matrix": {k: 3, v: 'foo'}}}, {$group: {_id: "$_id", "matrix": {$push: "$doc.matrix"}}})["result"]

{
  "_id" : ObjectId("545237a78916011a82e4a33e"),
  matrix: [
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:"foo"}, {k:4; v:".."}, {k:5; v:".."}, {k:6; v:".."}, {k:7; v:".."}]
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:"foo"}, {k:6; v:".."}, {k:7; v:".."}],
     [{k:1; v:".."}, {k:2; v:".."}, {k:3; v:"foo"}, {k:4; v:".."}, {k:5; v:".."}, {k:6; v:".."}, {k:7; v:".."}]
    ]
}

请注意,输出结构略有不同,即没有'doc'字段。但如果你能处理它,那么回答是正确的。