$add operation returns null value - mongodb

I have collection with document structure :
{
'year' : 2014,
'month' : 1
}
I am executing the following operation :
db.collname.aggregate(
[
{
$project : {
'year100' : {$multiply : ["$year" , 100]},
'result' : { '$add' : ['$year100', '$month'] }
}
}
]
);
I get the following result :
{
"result" : [
{
"_id" : ObjectId("5563596c515a88832210f0e4"),
"year100" : 201400.0000000000000000,
"result" : null
},
}
Why is add operation returuning null value as against to actual value ? Please help.

MongoDb not allow to used same fields in project to arithmetic operation instead of one $project used two different projects like this :
db.collname.aggregate({ $project : { 'year100' : {$multiply : ["$year" , 100]} ,"month":"$month"} },{"$project":{"year100":1,"result":{"$add":["$year100","$month"]}}})

Related

Mongo aggregation pipeline : How can I access one group stage variable in subsequent stage?

I have two collections here :
> db.Unit.find({}).limit(1).pretty()
{
"_id" : ObjectId("58b6878de1648d05903e1beb"),
"number" : "07in15in4",
"owner" : {
"name" : "vacant"
},
"floor" : 15,
"tower" : 4,
"VisitorLogs" : [
ObjectId("58b6878ee1648d05903e1d22"),
ObjectId("58b6878ee1648d05903e236e"),
ObjectId("58b6878ee1648d05903e23c9"),
ObjectId("58b6878ee1648d05903e2454"),
ObjectId("58b6878ee1648d05903e2915"),
ObjectId("58b6878ee1648d05903e2aae"),
ObjectId("58b6878ee1648d05903e2b93")
]
}
and
> db.VisitorLog.find({}).limit(1).pretty()
{ "_id" : ObjectId("58b6878fe1648d05903e2efa"), "purpose" : "WorkHere" }
VisitorLogs in the Unit collection refers to the second collection, i.e. VisitorLog.
I need to find the the units which have the maximum number of visits for each purpose.
I tried this in mongo shell:
units=db.Unit
units.aggregate([
{$match:{'VisitorLogs':{$gt:[]}}},
{$unwind:'$VisitorLogs'},
{$lookup:{
from:"VisitorLog",
localField:"VisitorLogs",
foreignField:"_id",
as:"log"}
},
{$group:{_id:{number:"$number", purpose:"$log.purpose"}, count:{$sum:1}}},
{$sort:{count:-1}},
{$group:{_id:"$_id.purpose", unit:{$first:"$_id.number"}}},
{$limit:10}
])
I get the following result :
{ "_id" : [ "Business" ], "unit" : "05in12in2" }
{ "_id" : [ "WorkHere" ], "unit" : "09in04in2" }
{ "_id" : [ "Casual" ], "unit" : "10in05in2" }
{ "_id" : [ "JobInterview" ], "unit" : "05in14in2" }
This means that, for example, unit number 05in12in2 had the maximum visits which had the purpose "Business"
I now want to get the number of "business" visits that 05in12in2 had.
I think its in "count" variable of the first group stage.
How do I access that ? I tried {$group:{_id:"$_id.purpose", unit:{$first:"$_id.number"}, visits:"$count"}}, in the second last stage, i.e just before the limit stage but I get error :
> units.aggregate([
... {$match:{'VisitorLogs':{$gt:[]}}},
... {$unwind:'$VisitorLogs'},
... {$lookup:{from:"VisitorLog", localField:"VisitorLogs", foreignField:"_id", as:"log"}},
... {$group:{_id:{number:"$number", purpose:"$log.purpose"}, count:{$sum:1}}},
... {$sort:{count:-1}},
... {$group:{_id:"$_id.purpose", unit:{$first:"$_id.number"}, visits:"$count"}},
... {$limit:10}
... ])
assert: command failed: {
"ok" : 0,
"errmsg" : "the group aggregate field 'visits' must be defined as an expression inside an object",
"code" : 15951
} : aggregate failed
_getErrorWithCode#src/mongo/shell/utils.js:25:13
doassert#src/mongo/shell/assert.js:13:14
assert.commandWorked#src/mongo/shell/assert.js:287:5
DBCollection.prototype.aggregate#src/mongo/shell/collection.js:1312:5
#(shell):1:1
Can someone please help me ?
You have this information, but you are cutting it off by the $group stage. Just change the stage to the following (notice the last argument):
{ $group : {
_id : "$_id.purpose",
unit : { $first : "$_id.number" },
visits : { $first : "$count" }
}}
The following outputs what I needed :
units.aggregate([
{$match:{'VisitorLogs':{$gt:[]}}},
{$unwind:'$VisitorLogs'},
{$lookup:{from:"VisitorLog", localField:"VisitorLogs", foreignField:"_id", as:"log"}},
{$group:{_id:{number:"$number", purpose:"$log.purpose"}, count:{$sum:1}}},
{$sort:{count:-1}},
{$group:{_id:"$_id.purpose", number:{$first:"$_id.number"}, visits:{$first:"$count"}}},
{$limit:10}
])

Positional operator and field limitation

In a find query projection, fields I specify after the positional operator are ignored and the whole document is always returned.
'myArray.$.myField' : 1 behave exactly like 'myArray.$' : 1
the positional operator selects the right document. But this document is quite big. I would like to project only 1 field from it.
Exemple:
db.getCollection('match').find({"participantsData.id" : 0001}, { 'participantsData.$.id': 1, })
here the response I have
{
"_id" : "myid",
"matchCreation" : 1463916465614,
"participantsData" : [
{
"id" : 0001,
"plenty" : "of",
"other" : "fields",
"and" : "subdocuments..."
}
]
}
This is what I want
{
"_id" : "myid",
"matchCreation" : 1463916465614,
"participantsData" : [
{
"id" : 0001
}
]
}
Is it possible with mongo?
Yes it can be done in mongo
Please try the below query
db.getCollection('match').find(
{"participantsData.id" : 0001},
{"participantsData.id": 1, "matchCreation": 1 })
This will give you the below result
{
"_id" : "myid",
"matchCreation" : 1463916465614,
"participantsData" : [
{
"id" : 1
}
]
}

Mongo query to return distinct count, large documents

I need to be able to get a count of distinct 'transactions' the problem I'm having is that using .distinct() comes back with an error because the documents too large.
I'm not familiar with aggregation either.
I need to be able to group it by 'agencyID' as you see below there are 2 different agencyID's
I need to be able to count transactions where the agencyID is 01721487 etc
db.myCollection.distinct("bookings.transactions").length
this doesn't work as I need to be able to group by agencyID and if there are too many results I get an error saying it's too large.
{
"_id" : ObjectId("5624a610a6e6b53b158b4744"),
"agencyID" : "01721487",
"paxID" : "-530189664",
"bookings" : [
{
"bookingID" : "24232",
"transactions" : [
{
"tranID" : "001",
"invoices" : [
{
"invNum" : "1312",
"type" : "r",
"inv_date" : "20150723",
"inv_time" : "0953",
"inv_val" : -300
}
],
"tranType" : "Fee",
"tranDate" : "20150723",
"tranTime" : "0952",
"opCode" : "admin",
"udf_1" : "j s"
}
],
"acctID" : "acct11",
"agt_id" : "xy"
}
],
"title" : "",
"firstname" : "",
"surname" : "f bar"
}
I've also tried this but it didn't work for me.
thank you for text data -
this is something you could play with:
db.kieron.aggregate([{
$unwind : "$bookings"
}, {
$match : {
"bookings.transactions" : {
$exists : true,
$not : {
$size : 0
}
}
}
}, {
$group : {
_id : "$agencyID",
count : {
$sum : {
$size : "$bookings.transactions"
}
}
}
}
])
as there is nested array we need to unwind it first, and then we can check size of inner array.
Happy reporting!

substract two date end return value

I need help to build a query to substract two dates in mongodb.
I have some documents like above :
{"_id" : "32472034809", "center": "102030", dateArq : 141010, inDate : "ISODate("2014-06-06T02:57:19.000-03:00)", biDate : ISODate("2014-06-07T02:57:19.000-03:00)"}
And Im trying to write a query
db.teste.aggregation([{$match : {dateArq : 141010}},{$project : {$subtract : ["$biDate" "$inDate"]}}])
In fact, I want to do : for each _id I want to result biDate - inDate , because I need to see if dateArq keep in a line constante.
In Oracle I did
select dateArq, (biDate - inDate) diff from teste where dateArq = 141010
Tks for help
The document and aggregation pipeline provided had syntax problems, and you needed to put a field name for the result of the $subtract, but otherwise your pipeline works for me:
> db.test.findOne()
{
"_id" : "32472034809",
"center" : "102030",
"dateArq" : 141010,
"inDate" : ISODate("2014-06-06T05:57:19Z"),
"biDate" : ISODate("2014-06-07T05:57:19Z")
}
> db.test.findOnedb.test.aggregate([
{ "$match" : { "dateArq" : 141010 } },
{ "$project" : { "dateDiff" : { "$subtract" : ["$biDate", "$inDate"] } } }
])
{ "_id" : "32472034809", "dateDiff" : NumberLong(86400000) }

How to update particular array element in MongoDB

I am newbie in MongoDB. I have stored data inside mongoDB in below format
"_id" : ObjectId("51d5725c7be2c20819ac8a22"),
"chrom" : "chr22",
"pos" : 17060409,
"information" : [
{
"name" : "Category",
"value" : "3"
},
{
"name" : "INDEL",
"value" : "INDEL"
},
{
"name" : "DP",
"value" : "31"
},
{
"name" : "FORMAT",
"value" : "GT:PL:GQ"
},
{
"name" : "PV4",
"value" : "1,0.21,0.00096,1"
}
],
"sampleID" : "Job1373964150558382243283"
I want to update the value to 11 which has the name as Category.
I have tried below query:
db.VariantEntries.update({$and:[ { "pos" : 117199533} , { "sampleID" : "Job1373964150558382243283"},{"information.name":"Category"}]},{$set:{'information.value':'11'}})
but Mongo replies
can't append to array using string field name [value]
How one can form a query which will update the particular value?
You can use the $ positional operator to identify the first array element to match the query in the update like this:
db.VariantEntries.update({
"pos": 17060409,
"sampleID": "Job1373964150558382243283",
"information.name":"Category"
},{
$set:{'information.$.value':'11'}
})
In MongoDB you can't adress array values this way. So you should change your schema design to:
"information" : {
'category' : 3,
'INDEL' : INDEL
...
}
Then you can adress the single fields in your query:
db.VariantEntries.update(
{
{"pos" : 117199533} ,
{"sampleID" : "Job1373964150558382243283"},
{"information.category":3}
},
{
$set:{'information.category':'11'}
}
)