MongoDB中是否有计算字段?

时间:2016-02-15 11:13:54

标签: mongodb nosql

MongoDB中是否有计算字段?

在SQL中,我可以这样做:

SELECT A+B AS C FROM MYTABLE WHERE C>10

我可以在MongoDB中做类似的事情吗?

更新

我做了投影:

db.segments.aggregate(
   [
      {
         $project: {
            "_id": 1,
            numberOfRestrictions: { $size: "$Speed Restrictions" }
         }
      }
   ]
)

它有效。

不幸的是,进一步的流水线操作不会:

db.segments.aggregate(
   [
      {
         $project: {
            "_id": 1,
            numberOfRestrictions: { $size: "$Speed Restrictions" }
         }
      },
      {
        $match: {
            "numberOfRestrictions": {
                "$gt": 1
            }
        }
      }
   ]
)

后期导致错误

The argument to $size must be an Array, but was of type: EOO

2 个答案:

答案 0 :(得分:5)

是。它被称为aggregation pipelines。具体而言,您需要使用 $project 阶段来创建 C 字段,然后使用 $match < / strong>阶段查找符合条件的所有文件。

实施例

让我们先创建一些文档:

for( var i = 1; i <=10; i++){
  db.agg.insert({a:i,b:i})
}

这导致集合看起来像这样:

> db.agg.find()
{ "_id" : ObjectId("56c1b5561a3b578f37a99d4d"), "a" : 1, "b" : 1 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d4e"), "a" : 2, "b" : 2 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d4f"), "a" : 3, "b" : 3 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d50"), "a" : 4, "b" : 4 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d51"), "a" : 5, "b" : 5 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d52"), "a" : 6, "b" : 6 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d53"), "a" : 7, "b" : 7 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d54"), "a" : 8, "b" : 8 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d55"), "a" : 9, "b" : 9 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d56"), "a" : 10, "b" : 10 }

查找C>的所有文件。 10

db.agg.aggregate([
    // You need to include all fields you want to have
    // in the resulting document within the $project stage
    { "$project":{ a:1, b:1, c:{ "$add": ["$a","$b"] }}},
    { "$match":{ c:{ "$gt":10 }}}
])

返回以下结果:

{ "_id" : ObjectId("56c1b5561a3b578f37a99d52"), "a" : 6, "b" : 6, "c" : 12 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d53"), "a" : 7, "b" : 7, "c" : 14 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d54"), "a" : 8, "b" : 8, "c" : 16 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d55"), "a" : 9, "b" : 9, "c" : 18 }
{ "_id" : ObjectId("56c1b5561a3b578f37a99d56"), "a" : 10, "b" : 10, "c" : 20 }

答案 1 :(得分:4)

使用聚合框架,可以使用 $project 运算符创建计算字段,使用 $match 运算符来过滤基于文档的文档计算字段:

db.collection.aggregate([
    {
        "$project": { "C": { "$add": [ "$A", "$B" ] } }
    },
    {
        "$match": { "C": { "$gt": 10 } }
    }
])