I have a collection with three documents:
{ "_id" : ObjectId("5bfe572882ace71e43703d15"), "event" : "Cdr", "privilege" : "cdr,all", "accountcode" : "", "source" : "22000", "destination" : "98723546", "destinationcontext" : "from-internal", "callerid" : "\"22000\" <22000>", "channel" : "SIP/22000-00000005", "destinationchannel" : "SIP/9144502101-00000006", "lastapplication" : "Dial", "lastdata" : "SIP/9144502101/98723546,300,Tb(func-apply-sipheaders^s^1)", "starttime" : "2018-11-28 15:51:47", "answertime" : "", "endtime" : "2018-11-28 15:51:52", "duration" : "5", "billableseconds" : "0", "disposition" : "NO ANSWER", "amaflags" : "DOCUMENTATION", "uniqueid" : "1543395107.5", "userfield" : "" }
{ "_id" : ObjectId("5bfe5829b3a9321f241f10f2"), "event" : "Cdr", "privilege" : "cdr,all", "accountcode" : "", "source" : "98723546", "destination" : "s", "destinationcontext" : "ivr-1", "callerid" : "\"98723546\" <98723546>", "channel" : "SIP/9144502101-00000007", "destinationchannel" : "", "lastapplication" : "BackGround", "lastdata" : "custom/int1", "starttime" : "2018-11-28 15:56:03", "answertime" : "2018-11-28 15:56:03", "endtime" : "2018-11-28 15:56:09", "duration" : "6", "billableseconds" : "6", "disposition" : "ANSWERED", "amaflags" : "DOCUMENTATION", "uniqueid" : "1543395363.7", "userfield" : "" }
{ "_id" : ObjectId("5bfe5833b3a9321f241f10f4"), "event" : "Cdr", "privilege" : "cdr,all", "accountcode" : "", "source" : "98723546", "destination" : "22000", "destinationcontext" : "from-did-direct", "callerid" : "\"98723546\" <98723546>", "channel" : "SIP/9144502101-00000008", "destinationchannel" : "SIP/22000-00000009", "lastapplication" : "Dial", "lastdata" : "SIP/22000,,HhtrIb(func-apply-sipheaders^s^1)", "starttime" : "2018-11-28 15:56:12", "answertime" : "2018-11-28 15:56:12", "endtime" : "2018-11-28 15:56:19", "duration" : "7", "billableseconds" : "7", "disposition" : "NO ANSWER", "amaflags" : "DOCUMENTATION", "uniqueid" : "1543395372.8", "userfield" : "" }
I want to sum $duration and try command:
db.cdrs.aggregate([{$group: { _id: "$event", total: { $sum: "$duration"}}}])
Result return:
{ "_id" : "Cdr", "total" : 0 }
How to use $sum return result Sum duration of three documents(5 + 6 + 7 = 18)?
You can sum duration by converting string to Int
Its work on Mongo version 4.0
Example :
db.getCollection('A').aggregate([{
$addFields: {
convertedDuration: { $toInt: "$duration" },
} },
{
$group: { _id: "$event", total: { $sum: "$convertedDuration"} }
}
])
reference Link : link1, link2
Here is the working example of your query, click on run at the top. In your Documents, the duration is stored as String, I guess mongoDB won't convert and sum the values, please change your duration to Number while storing. Your query is fine.
Related
I have data in a collection ex:"jobs". I am trying to copy specific data from "jobs" after every 2 hours to a new collection (which may not exist initially) and also add a new key to the copied data.
I have been trying with this query to copy the data:
db.getCollection("jobs").aggregate([{ $match: { "job_name": "UploadFile", "created_datetime" : {"$gte":"2021-08-18 12:00:00"} } },{"$merge":{into: {coll : "reports"}}}])
But after this, the count in "reports" collection is 0. Also, how can I update the documents (with an extract key "report_name") without using an extra updateMany() query?
The data in jobs collection is as shown:
{
"_id" : ObjectId("60fa8e8283dc22799134dc6f"),
"job_id" : "408a5654-9a89-4c15-82b4-b0dc894b19d7",
"job_name" : "UploadFile",
"data" : {
"path" : "share://LOCALNAS/Screenshot from 2021-07-23 10-34-34.png",
"file_name" : "Screenshot from 2021-07-23 10-34-34.png",
"parent_path" : "share://LOCALNAS",
"size" : 97710,
"md5sum" : "",
"file_uid" : "c4411f10-a745-48d0-a55d-164707b7d6c2",
"version_id" : "c3dfd31a-80ba-4de0-9115-2d9b778bcf02",
"session_id" : "c4411f10-a745-48d0-a55d-164707b7d6c2",
"resource_name" : "Screenshot from 2021-07-23 10-34-34.png",
"metadata" : {
"metadata" : {
"description" : "",
"tag_ids" : [ ]
},
"category_id" : "60eed9ea33c690a0dfc89b41",
"custom_metadata" : [ ]
},
"upload_token" : "upload_token_c5043927484e",
"upload_url" : "/mnt/share_LOCALNAS",
"vfs_action_handler_id" : "91be4282a9ad5067642cdadb75278230",
"element_type" : "file"
},
"user_id" : "60f6c507d4ba6ee28aee5723",
"node_id" : "syeda",
"state" : "COMPLETED",
"priority" : 2,
"resource_name" : "Screenshot from 2021-07-23 10-34-34.png",
"group_id" : "upload_group_0babf8b7ce0b",
"status_info" : {
"progress" : 100,
"status_msg" : "Upload Completed."
},
"error_code" : "",
"error_message" : "",
"created_datetime" : ISODate("2021-07-23T15:10:18.506Z"),
"modified_datetime" : ISODate("2021-07-23T15:10:18.506Z"),
"schema_version" : "1.0.0",
}
Your $match stage contains a condition which takes created_datetime as string while in your sample data it is an ISODate. Such condtion won't return any document, try:
{
$match: {
"job_name": "UploadFile",
"created_datetime": {
"$gte": ISODate("2021-07-01T12:00:00.000Z")
}
}
}
Mongo Playground
My MongoDB contains the following data
{
"_id" : ObjectId("5c1b742eb1829b69963029e8"),
"duration" : 12,
"cost" : 450,
"tax" : 81,
"tags" : [],
"participants" : [
ObjectId("5c1b6a8f348ddb15e4a8aac7"),
ObjectId("5c1b742eb1829b69963029e7")
],
"initiatorId" : ObjectId("5c1b6a8f348ddb15e4a8aac7"),
"context" : "coach",
"accountId" : ObjectId("5bdfe7b01cbf9460c9bb5d68"),
"status" : "over",
"webhook" : "http://d4bdc1ef.ngrok.io/api/v1/webhook_callback",
"hostId" : "5be002109a708109f862a03e",
"createdAt" : ISODate("2018-12-20T10:51:26.143Z"),
"updatedAt" : ISODate("2018-12-20T10:51:44.962Z"),
"__v" : 0,
"endedAt" : ISODate("2018-12-20T10:51:44.612Z"),
"startedAt" : ISODate("2018-12-20T10:51:32.992Z"),
"type" : "voip"
}
{
"_id" : ObjectId("5c1b7451b1829b69963029ea"),
"duration" : 1,
"cost" : 150,
"tax" : 27,
"tags" : [],
"participants" : [
ObjectId("5c1b6a8f348ddb15e4a8aac7"),
ObjectId("5c1b7451b1829b69963029e9")
],
"initiatorId" : ObjectId("5c1b6a8f348ddb15e4a8aac7"),
"context" : "coach",
"accountId" : ObjectId("5bdfe7b01cbf9460c9bb5d68"),
"status" : "over",
"webhook" : "http://d4bdc1ef.ngrok.io/api/v1/webhook_callback",
"hostId" : "5be002109a708109f862a03e",
"createdAt" : ISODate("2018-12-20T10:52:01.560Z"),
"updatedAt" : ISODate("2018-12-20T10:52:08.018Z"),
"__v" : 0,
"endedAt" : ISODate("2018-12-20T10:52:07.667Z"),
"startedAt" : ISODate("2018-12-20T10:52:06.762Z"),
"type" : "voip"
}
I want to get the total duration (sum of duration field) for a particular accountID where status is equals to "over" for a particular date range. Anyway to accomplish this using PyMongo? I am unable to form the query
Well I was doing some pretty basic mistakes while converting the query to PyMongo aggregation function. All I would say is be careful with the query structure format and especially the keys are to be encapsulated within quotes(""). To solve this all I have to do was
from bson.objectid import ObjectId
pipe = [
{"$match": {"accountId": ObjectId(accountId),
"status": "over",
"startedAt": {"$gte": startDate,
"$lte": EndDate
}
}},
{"$project": {"readableDate":
{"$dateToString":
{"format": "%Y-%m-%d", "date": "$startedAt"}},
"accountId": str("$accountId"),
"duration": "$duration"
}},
{"$group": {"_id": {"date": "$readableDate",
"accountId": str("$accountId")}, "totalCallDuration": {"$sum": "$duration"}}}]
for doc in db.VoiceCall.aggregate(pipe):
print(doc)
Just a reminder : the startDate and EndDate are in Python datetime format.
I have two case ,first case: where in my key has reference to the same collection ,is this correct way to reference ?,if yes ! how to de-ref/link in node js ?,if not how to reference fom the same collection
{
"_id" : ObjectId("53402597d852426020000002"),
"address" : {
"$ref" : "home_adress"
},
"contact" : "987654321",
"dob" : "01-01-1991",
"name" : "Tom Benzamin",
"Post_address" : {
"$ref" : "home_adress"
},
"home_adress":"Street 1, NY"}
case two: reference to a different collection(DBRefs),How to detect the reference and send the second query to fetch the referenced value ?
{
"_id" : ObjectId("53402597d852426020000002"),
"address" : {
"$ref" : "address_home",
"$id" : ObjectId("534009e4d852427820000002"),
"$db" : "ref"
},
"contact" : "987654321",
"dob" : "01-01-1991",
"name" : "Tom Benzamin"}
{
"_id" : ObjectId("534009e4d852427820000002"),
"building" : "22 A, Indiana Apt",
"pincode" : 123456,
"city" : "Los Angeles",
"state" : "California"}
I have a mongo database running in cmd.
There is a collection named usercollection.
And there is also some documents which I'm getting by typing in mongo shell:
db.usercollection.find().sort({score: -1}).pretty()
Output:
{
"_id" : ObjectId("57501b2d7ef17cd8c1bd63bc"),
"name" : "QWERTY",
"score" : "100",
"link" : "http://qwerty.com"
}
{
"_id" : ObjectId("5750199819433f80da88c847"),
"name" : "Adam Sandler",
"score" : "222",
"link" : "http://sandler.com"
}
{
"_id" : ObjectId("57501af57ef17cd8c1bd63bb"),
"name" : "gfhfghfghguy",
"score" : "5",
"link" : "http://dsad.com"
}
{
"_id" : ObjectId("57501bb47ef17cd8c1bd63bd"),
"name" : "Test name",
"score" : "50",
"link" : "http://fdsfds.cpm"
}
{
"_id" : ObjectId("574f4a9dab868fdc896d11b4"),
"name" : "Rich Man",
"score" : "500",
"link" : "http://jikl.me"
}
{
"_id" : ObjectId("574f50f1fbd256888ffa248d"),
"name" : "lfgfgff",
"score" : "9",
"link" : "http://oh.com"
}
{
"_id" : ObjectId("574f5324fbd256888ffa248e"),
"name" : "test name",
"score" : "9",
"link" : "http://dsad.com"
}
The problem is that I'm trying to sort these documents from one with highest score to one with lowest score and it's output is completely random(
I'm displaying that documents on the website using node.js and the result is the same as in the console.
Try with :
db.usercollection.find().sort({score: 'desc'}).pretty()
I have a collection "image" and "image_ids "in my mongoDB:
image:
{
"_id" : ObjectId("542e65368a1cec1227ae2bac"),
"reference" : "5424991"
}
images_ids:
{
"_id" : ObjectId("542e652995ac12ed3fecb85f"),
"image" : "D0000001.PNG",
"fid" : ObjectId("542e65368a1cec1227ae2bac"),
"reference" : "5424991"
}
How I can be able to display D0000001.PNG with NodeJS? I mean, to do the link with and API.
[EDIT] we have also
fs.chunks:
{
"_id" : ObjectId("542e684a8a1cec178a172673"),
"n" : 1,
"data" : BinData(0,"2N6DSSfbCN/LLacNDYrJUQDEZgimMUwFpQGoJP0RU19Bi4PM82DjrUnKhE/P9v7P8ZveD1oDpFBM0iml9NE3WQmAvYFoG+nhD73Jm4N9b4LpylaAN5Ef+gVdgGSTAfSUwOikXoVick5pSQCkRmTCU5NT9VVfjHdAx74/ZhFRj+TIRjzlAhzkACBElzgMwGCo7tX+FYrpQLJ5KRmXiwFFwsNtHHzXiK1eu+CG1FumhGpA/qdG8CdDgD1xUHEcerMGO/eLGR9ML7ni/VjXxWzqp2j5DG2/WuKNv7xd3Kz/vr0MctJhuaBIl35YrKhdLnzqDa0uDa6bm4jz+eNyAI2hQbayGo4kVPFe8W7wFpY7qfBvnB9kbocxfZSdADDUNwYaydpT8lIcKEN9XfQJOYZvHp0El"),
"files_id" : ObjectId("542e684a8a1cec178a172671")
}
fs.files:
{
"_id" : ObjectId("542e65378axdeckhb0"),
"uploadDate" : ISODate("2012-11-01"),
"length" : 15673,
"chunkSize" : 33222,
"md5" : "f66e6654854a28e3672cfhds334d223b55a1"
}
Thanks for your help !