user808186
user808186

Reputation: 27

MongoDB aggregation framework $subtract

I'm want use mongodb to achieve simple query like mysql "select a-b from table", but aggregation framework query result is not right.

data:

{ "_id" : ObjectId("511223348a88785127a0d13f"), "a" : 1, "b" : 1, "name" : "xxxxx0" }
{ "_id" : ObjectId("511223348a88785127a0d13f"), "a" : 2, "b" : 2, "name" : "xxxxx1" }

mongodb cmd:

db.site.aggregate([
  { $match: { 
    "a" : {$exists:true},
    "b" : {$exists:true},
    }
  },
  { $project: { _id : 0,name : 1, 
    r1: {$subtract:["$a", "$b"]} }
  },
  { $limit: 100 },
]);




"result" : [
        {
            "name" : "xxxx1",
            "r1" : -1
        },
        {
            "name" : "xxxx0",
            "r1" : -2
        },
]

Upvotes: 1

Views: 3556

Answers (1)

Sammaye
Sammaye

Reputation: 43884

I cannot replicate your behaviour:

> db.tg.find()
{ "_id" : ObjectId("511223348a88785127a0d13f"), "a" : 1, "b" : 1, "name" : "xxxxx0" }
> db.tg.aggregate([{ $match: { "a" : {$exists:true}, "b" : {$exists:true} } }, { $project: { _id : 0,name : 1, r1: {$subtract:["$a", "$b"]} }}, { $limit: 100 }])
{ "result" : [ { "name" : "xxxxx0", "r1" : 0 } ], "ok" : 1 }

Can you give us a little more info like your MongoDB version?

Upvotes: 2

Related Questions