Related
That's my mongodb data base shown in cmd as you see there is a field named test which exist a time and one other time didn't exist I want to write a get method to find field which contain only imei without test
router.get('/', (req, res, next) => {
Post.find()
.then((posts) => {
res.json(posts);
console.log(posts);
console.log("ok" + JSON.stringify(req.body) + req.body.imei);
})
.catch(err => console.log(err))
});
Here the get method it show me all data base I want to customize it.
{
"_id" : ObjectId("5eb6b927e1c2916320ab28de"),
"imei" : {
"name" : "50"
},
"test" : {
"batterieState" : "0"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bbbc09183a3e4c833ebe"),
"imei" : {
"name" : "xx"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bbcb09183a3e4c833ebf"),
"imei" : {
"name" : ""
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bc7809183a3e4c833ec0"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bcc309183a3e4c833ec1"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bd1209183a3e4c833ec2"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bdc609183a3e4c833ec3"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6be4609183a3e4c833ec4"),
"imei" : {
"name" : "xx"
},
"test" : {
"tactileState" : "0",
"pixelState" : "0",
"greyState" : "0"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6be6609183a3e4c833ec5"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6beef09183a3e4c833ec6"),
"imei" : {
"name" : "xx"
},
"test" : {
"tactileState" : "0",
"pixelState" : "0",
"greyState" : "0"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bf8709183a3e4c833ec7"),
"imei" : {
"name" : "865566048694354"
},
"test" : {
"tactileState" : "ignore",
"pixelState" : "ignore",
"greyState" : "ignore"
},
"__v" : 0
}
I want some help for this to write this method correctly to get only fields with imei only and without test.
Use this query
Post.find({
imei: {
$exists: true
},
test: {
$exists: false
}
})
Docs of $exists operator
This is the query I've been using for getting some random uniqueXperiences, in that I've lookup xpert and I want to project its _id and name.
db.getCollection('uniquexperiences').aggregate([{
'$sample': {
'size': 2
}
}, {
'$lookup': {
'from': 'users',
'as': 'Xpert',
'pipeline':[{
'$project': {
'name': 1
}
}]
}
}]);
The output I'm getting is something like this:
/* 1 */
{
"_id" : ObjectId("5b558b5997199d3ec4953e6b"),
"updatedBy" : ObjectId("5b433dbf6a93e56a21f610eb"),
"updatedAt" : ISODate("2018-10-10T10:56:36.952Z"),
"createdBy" : ObjectId("5b433dbf6a93e56a21f610eb"),
"createdAt" : ISODate("2018-07-23T08:01:29.125Z"),
"title" : "Horse riding at EIRS",
"organisationFlag" : false,
"xperienceSubCategory" : [
ObjectId("5b4de8199f07bf0b303b8c5f")
],
"xpert" : [
ObjectId("5b51b054054a962cc6f914db")
],
"description" : "Beautiful rugged landscape makes Ladakh stand apart in the country. There is indeed so much that needs to be explored here and little did we know that amongst the best ways to explore this place is riding a horse. In the remote places like Zanskar Valley, where paved roads are rare and motor biking is not every ones cup of tea, horses make an incredible means of travel. One can access to Zangla, Penzela Pass, Panikhar Fort and Zongkhul, Stongdey and Gelugpa monasteries on a horseback.",
"__v" : 4,
"images" : [
{
"public_id" : "dotttg3xm0vvqygr4n1w",
"version" : 1537776979,
"signature" : "4fb562aa4115941e78f773dd11ed6be37a337acd",
"width" : 1280,
"height" : 640,
"format" : "jpg",
"resource_type" : "image",
"url" : "http://res.cloudinary.com/xplr-qa/image/upload/v1537776979/dotttg3xm0vvqygr4n1w.jpg",
"secure_url" : "https://res.cloudinary.com/xplr-qa/image/upload/v1537776979/dotttg3xm0vvqygr4n1w.jpg",
"_id" : ObjectId("5ba89d55ac69b4784a4f3a1f")
},
{
"public_id" : "cfdepst0r2wz39rowvzd",
"version" : 1537776980,
"signature" : "e770b7354c01ffce61c2e3cb83c79456dacc5438",
"width" : 2100,
"height" : 1526,
"format" : "jpg",
"resource_type" : "image",
"url" : "http://res.cloudinary.com/xplr-qa/image/upload/v1537776980/cfdepst0r2wz39rowvzd.jpg",
"secure_url" : "https://res.cloudinary.com/xplr-qa/image/upload/v1537776980/cfdepst0r2wz39rowvzd.jpg",
"_id" : ObjectId("5ba89d55ac69b4784a4f3a1e")
},
{
"public_id" : "lqfk6twitfefrjq1h2jq",
"version" : 1537776979,
"signature" : "ad1e0079a9419bde0047228446be17218117cf2e",
"width" : 2500,
"height" : 1666,
"format" : "jpg",
"resource_type" : "image",
"url" : "http://res.cloudinary.com/xplr-qa/image/upload/v1537776979/lqfk6twitfefrjq1h2jq.jpg",
"secure_url" : "https://res.cloudinary.com/xplr-qa/image/upload/v1537776979/lqfk6twitfefrjq1h2jq.jpg",
"_id" : ObjectId("5ba89d55ac69b4784a4f3a1d")
}
],
"source" : "",
"price" : 400,
"meetingLocation" : [],
"coordinates" : [
72.955162,
19.172098
],
"purchaseCount" : 10,
"Xpert" : [
{
"_id" : ObjectId("5b518101752982066a0dcc08"),
"name" : {
"last" : "Bourdain",
"first" : "Anthony"
}
},
{
"_id" : ObjectId("5b51b054054a962cc6f914db"),
"name" : {
"last" : "Yane",
"first" : "Sid"
}
},
{
"_id" : ObjectId("5b51c00597199d3ec4953e68"),
"name" : {
"last" : "ipsum",
"first" : "Lorem"
}
},
{
"_id" : ObjectId("5b59a8cdca722c3177cf3e63"),
"name" : {
"last" : "Lorem",
"first" : "Test"
}
},
{
"_id" : ObjectId("5b5eea6e2d4b6a04b2d9d599")
},
{
"_id" : ObjectId("5b5f02e22d4b6a04b2d9d5f1")
},
{
"_id" : ObjectId("5b60364f9e866d6453fef3ea"),
"name" : {
"last" : "Lorem",
"first" : "ipsum"
}
},
{
"_id" : ObjectId("5b6d70f96aaf19087ac6d9e9"),
"name" : {
"first" : "Indrajit",
"last" : "Jadhav"
}
},
{
"_id" : ObjectId("5b6d81953da5c50974642974"),
"name" : {
"last" : "Lorem",
"first" : "shin"
}
},
{
"_id" : ObjectId("5b6d831f3da5c50974642975"),
"name" : {
"last" : "Lorem",
"first" : "Shin "
}
},
{
"_id" : ObjectId("5b6d83b83da5c50974642976"),
"name" : {
"last" : "wert",
"first" : "fadsg"
}
},
{
"_id" : ObjectId("5b6d83ee3da5c50974642977"),
"name" : {
"last" : "asdfsaf",
"first" : "sadf"
}
},
{
"_id" : ObjectId("5b7ba46cd0e5fa137805552b"),
"name" : {
"first" : "Vivek",
"last" : "Pandey"
}
},
{
"_id" : ObjectId("5b7bb359d0e5fa13780555a9"),
"name" : {
"first" : "theamalageeks",
"last" : "null"
}
},
{
"_id" : ObjectId("5b7bd19ed0e5fa137805565d"),
"name" : {
"first" : "Anikesh",
"last" : "Baburanjan"
}
},
{
"_id" : ObjectId("5b7fa359211f5649518ae311"),
"name" : {
"first" : "Akhsay",
"last" : "Gaikwad"
}
},
{
"_id" : ObjectId("5b80181fab8747537011be5c"),
"name" : {
"first" : "Sagar",
"last" : "Bisen"
}
},
{
"_id" : ObjectId("5b83f1c5de663c0dcccfb483"),
"name" : {
"first" : "INDRAJIT",
"last" : "JADHAV"
}
},
{
"_id" : ObjectId("5b92154efc790f18121f9e02"),
"name" : {
"first" : "sagar",
"last" : "bisen"
}
},
{
"_id" : ObjectId("5ba39c509350135c9951ecb6"),
"name" : {
"first" : "Anikesh",
"last" : "Baburajan"
}
},
{
"_id" : ObjectId("5ba3b8e79350135c9951ecb7"),
"name" : {
"first" : "Anurag",
"last" : "Banerjee"
}
},
{
"_id" : ObjectId("5ba3c14e9350135c9951ecb8"),
"name" : {
"first" : "Dave",
"last" : "Jhala"
}
},
{
"_id" : ObjectId("5ba4dfcf6bb5277e1d7db2af"),
"name" : {
"first" : "Mark",
"last" : "Henry"
}
},
{
"_id" : ObjectId("5ba4e1c0452d7e01ce3dd34e"),
"name" : {
"first" : "Ankita",
"last" : "Mestry"
}
},
{
"_id" : ObjectId("5ba7795b452d7e01ce3dd34f"),
"name" : {
"first" : "Abhishek",
"last" : "Gupta"
}
},
{
"_id" : ObjectId("5ba9ec5844996a4be81a0c12"),
"name" : {
"first" : "Neeti",
"last" : "Patil"
}
},
{
"_id" : ObjectId("5baa1abf44996a4be81a0c13"),
"name" : {
"first" : "Krishna",
"last" : "S"
}
},
{
"_id" : ObjectId("5bb481d4c77dd914de2cb2f7"),
"name" : {
"first" : "krishna",
"last" : "shetty"
}
}
]
}
/* 2 */
{
"_id" : ObjectId("5bab23c897f85d07b9235a19"),
"updatedBy" : ObjectId("5b433dbf6a93e56a21f610eb"),
"updatedAt" : ISODate("2018-10-10T10:57:01.790Z"),
"createdBy" : ObjectId("5b433dbf6a93e56a21f610eb"),
"createdAt" : ISODate("2018-09-26T06:14:32.637Z"),
"xpert" : ObjectId("5ba4dfcf6bb5277e1d7db2af"),
"title" : "Mumbai Temples Tour",
"images" : [
{
"public_id" : "uvmemwfwmjfl7pmv4upk",
"version" : 1537943055,
"signature" : "5358320e4f396a2ee980e767a16d4a92228c95d6",
"width" : 1440,
"height" : 900,
"format" : "jpg",
"resource_type" : "image",
"url" : "http://res.cloudinary.com/xplr-qa/image/upload/v1537943055/uvmemwfwmjfl7pmv4upk.jpg",
"secure_url" : "https://res.cloudinary.com/xplr-qa/image/upload/v1537943055/uvmemwfwmjfl7pmv4upk.jpg",
"_id" : ObjectId("5bab260f97f85d07b9235a20")
},
{
"public_id" : "zztqwdbl7ejccxmougad",
"version" : 1537943055,
"signature" : "bcb413431d518b243d801f92ff9cf0a8f9bd7682",
"width" : 1920,
"height" : 1080,
"format" : "jpg",
"resource_type" : "image",
"url" : "http://res.cloudinary.com/xplr-qa/image/upload/v1537943055/zztqwdbl7ejccxmougad.jpg",
"secure_url" : "https://res.cloudinary.com/xplr-qa/image/upload/v1537943055/zztqwdbl7ejccxmougad.jpg",
"_id" : ObjectId("5bab260f97f85d07b9235a1f")
}
],
"organisationFlag" : false,
"xperienceSubCategory" : [
ObjectId("5b616b4c9e866d6453fef3eb")
],
"description" : "Global Vipassana Pagoda is an expression of our gratitude towards the Buddha who strived for incalculable aeons to reach Supreme Enlightenment.",
"__v" : 4,
"price" : 800,
"source" : "",
"meetingLocation" : [],
"coordinates" : [
72.955162,
19.172098
],
"primaryLocation" : ObjectId("5bacb0192e0b2751f0f7f057"),
"purchaseCount" : 20,
"Xpert" : [
{
"_id" : ObjectId("5b518101752982066a0dcc08"),
"name" : {
"last" : "Bourdain",
"first" : "Anthony"
}
},
{
"_id" : ObjectId("5b51b054054a962cc6f914db"),
"name" : {
"last" : "Yane",
"first" : "Sid"
}
},
{
"_id" : ObjectId("5b51c00597199d3ec4953e68"),
"name" : {
"last" : "ipsum",
"first" : "Lorem"
}
},
{
"_id" : ObjectId("5b59a8cdca722c3177cf3e63"),
"name" : {
"last" : "Lorem",
"first" : "Test"
}
},
{
"_id" : ObjectId("5b5eea6e2d4b6a04b2d9d599")
},
{
"_id" : ObjectId("5b5f02e22d4b6a04b2d9d5f1")
},
{
"_id" : ObjectId("5b60364f9e866d6453fef3ea"),
"name" : {
"last" : "Lorem",
"first" : "ipsum"
}
},
{
"_id" : ObjectId("5b6d70f96aaf19087ac6d9e9"),
"name" : {
"first" : "Indrajit",
"last" : "Jadhav"
}
},
{
"_id" : ObjectId("5b6d81953da5c50974642974"),
"name" : {
"last" : "Lorem",
"first" : "shin"
}
},
{
"_id" : ObjectId("5b6d831f3da5c50974642975"),
"name" : {
"last" : "Lorem",
"first" : "Shin "
}
},
{
"_id" : ObjectId("5b6d83b83da5c50974642976"),
"name" : {
"last" : "wert",
"first" : "fadsg"
}
},
{
"_id" : ObjectId("5b6d83ee3da5c50974642977"),
"name" : {
"last" : "asdfsaf",
"first" : "sadf"
}
},
{
"_id" : ObjectId("5b7ba46cd0e5fa137805552b"),
"name" : {
"first" : "Vivek",
"last" : "Pandey"
}
},
{
"_id" : ObjectId("5b7bb359d0e5fa13780555a9"),
"name" : {
"first" : "theamalageeks",
"last" : "null"
}
},
{
"_id" : ObjectId("5b7bd19ed0e5fa137805565d"),
"name" : {
"first" : "Anikesh",
"last" : "Baburanjan"
}
},
{
"_id" : ObjectId("5b7fa359211f5649518ae311"),
"name" : {
"first" : "Akhsay",
"last" : "Gaikwad"
}
},
{
"_id" : ObjectId("5b80181fab8747537011be5c"),
"name" : {
"first" : "Sagar",
"last" : "Bisen"
}
},
{
"_id" : ObjectId("5b83f1c5de663c0dcccfb483"),
"name" : {
"first" : "INDRAJIT",
"last" : "JADHAV"
}
},
{
"_id" : ObjectId("5b92154efc790f18121f9e02"),
"name" : {
"first" : "sagar",
"last" : "bisen"
}
},
{
"_id" : ObjectId("5ba39c509350135c9951ecb6"),
"name" : {
"first" : "Anikesh",
"last" : "Baburajan"
}
},
{
"_id" : ObjectId("5ba3b8e79350135c9951ecb7"),
"name" : {
"first" : "Anurag",
"last" : "Banerjee"
}
},
{
"_id" : ObjectId("5ba3c14e9350135c9951ecb8"),
"name" : {
"first" : "Dave",
"last" : "Jhala"
}
},
{
"_id" : ObjectId("5ba4dfcf6bb5277e1d7db2af"),
"name" : {
"first" : "Mark",
"last" : "Henry"
}
},
{
"_id" : ObjectId("5ba4e1c0452d7e01ce3dd34e"),
"name" : {
"first" : "Ankita",
"last" : "Mestry"
}
},
{
"_id" : ObjectId("5ba7795b452d7e01ce3dd34f"),
"name" : {
"first" : "Abhishek",
"last" : "Gupta"
}
},
{
"_id" : ObjectId("5ba9ec5844996a4be81a0c12"),
"name" : {
"first" : "Neeti",
"last" : "Patil"
}
},
{
"_id" : ObjectId("5baa1abf44996a4be81a0c13"),
"name" : {
"first" : "Krishna",
"last" : "S"
}
},
{
"_id" : ObjectId("5bb481d4c77dd914de2cb2f7"),
"name" : {
"first" : "krishna",
"last" : "shetty"
}
}
]
}
Instead of getting multiple Xperts in Xpert
Now I want to match the Xpert fields _id with xpert field of the output
Use the below aggregation.
Use $lookup pipeline variant. Let expression checks for a array type for xpert and converts into array when it is not. $match to collect all the matching users documents. $project to output name from user document.
db.uniquexperiences.aggregate([
{"$sample":{"size":2}},
{"$lookup":{
"from":"users",
"let":{"xpert":{"$cond":[{"$isArray":"$xpert"},"$xpert",["$xpert"]]}},
"pipeline":[
{"$match":{"$expr":{"$in":["$_id","$$xpert"]}}},
{"$project":{"name":1}}],
"as":"Xpert"
}}
])
There is a collection in MongoDB like:
{
"_id" : ObjectId("5bcc4c7d1e2c701be024de99"),
"className" : "Class 10",
"gradeLevel" : "10th",
"subjectName" : "Math",
"teacherId" : "abcd#gmail.com",
"__v" : 0
},
{
"_id" : ObjectId("5bd45277f5b9430013f4a604"),
"className" : "Class 11",
"gradeLevel" : "11th",
"subjectName" : "Maths",
"teacherId" : "abcd#gmail.com",
"__v" : 0
},
{
"_id" : ObjectId("5bd470fe452cb33af4b8407a"),
"className" : "Class 10",
"gradeLevel" : "12th",
"subjectName" : "Math",
"teacherId" : "abcd#gmail.com",
"__v" : 0
},
Now I want to fetch those documents with values of_id:
ObjectId("5bd45277f5b9430013f4a604"), ObjectId("5bd470fe452cb33af4b8407a").
I am using mongoose and node.js. So please tell me is there any way to do this.
Model.find({ _id: { $in: ['5bd45277f5b9430013f4a604', '5bd470fe452cb33af4b8407a'] } })
.then(docs => console.log(docs))
.catch(err => console.log(err));
I have to find "exitState" : this is single document , if multiple documents how to find.
{
"_id" : "abc",
"exitType" : "Hang",
"exitState" : "INDIA",
"outcome" : "Successful",
"CEV" : [
{
"LogID" : "CEV",
"ReportingMode" : "N",
"Log_DateTime" : "02:23:2016 00:17:48:913",
"Log_TS" : NumberLong(1456186668913),
"ServiceType" : "TEL",
"MsgID" : "25000",
"SysName" : "test123",
"ProcessID" : "9611",
"Port" : "0",
"ModuleName" : "ArcCDR::CDR_CustomEvent",
"AppName" : "testVXML2",
"MsgTxt" : "abc::24::Test::outcome=Successful$$$exitType=Hang$$$exitState=INDIA",
"Record_Key" : "abc",
"Token1" : "24",
"CustomerName" : "Test",
"CEV_MsgTxt" : "outcome=Successful$$$exitType=Hang$$$exitState=INDIA",
"outcome" : "Successful",
"exitType" : "Hang",
"exitState" : "INDIA"
}
],
"language" : "ENGLISH",
"SC_TS" : ISODate("2016-02-23T00:17:06.060+0000"),
"SC_TimeMS" : NumberLong(1456186626060),
"CDR_SC" : {
"LogID" : "CDR",
"ReportingMode" : "N",
"Log_DateTime" : "02:23:2016 00:17:06:060",
"Log_TS" : NumberLong(1456186626060),
"ServiceType" : "TEL",
"MsgID" : "20010",
"SysName" : "test123",
"ProcessID" : "9611",
"Port" : "0",
"ModuleName" : "TEL_AnswerCall",
"AppName" : "testVXML2",
"MsgTxt" : "abc:SC:testVXML2:452:607856:0223201600170606::",
"Record_Key" : "abc",
"CDR_Type" : "SC",
"Token2" : "testVXML2",
"Token3" : "452",
"Token4" : "607856",
"Token5" : "0223201600170606"
},
" SC_TS_TZ" : ISODate("2016-02-23T00:17:06.060+0000"),
"EC_TS" : ISODate("2016-02-23T00:17:48.910+0000"),
"EC_TS_TZ" : ISODate("2016-02-23T00:17:48.910+0000"),
"EC_TimeMS" : NumberLong(1456186668910),
"CDR_EC" : {
"LogID" : "CDR",
"ReportingMode" : "N",
"Log_DateTime" : "02:23:2016 00:17:48:910",
"Log_TS" : NumberLong(1456186668910),
"ServiceType" : "TEL",
"MsgID" : "20011",
"SysName" : "test123",
"ProcessID" : "9611",
"Port" : "0",
"ModuleName" : "TEL_SRRecognizeV2",
"AppName" : "testVXML2",
"MsgTxt" : "abc:EC:02:0223201600174891::",
"Record_Key" : "abc",
"CDR_Type" : "EC",
"Token2" : "02",
"Token3" : "0223201600174891"
},
"CustomerName" : "Test"
}
Below is my query but unable to find exitState in all documents . Can you please?
dbo.ProductModel.aggregate([
{$match: {"EC_TS":{$gte:new Date(start.toISOString()), $lte:new Date(end.toISOString())}} },
{$group:
{_id: '$exitState', count : {$sum: 1} }
}
]).toArray(function(err, result4) {
console.log(+ result4[0]["exitState"]);
console.log("Total exitState=" + result4[0]["total"]);
q4result=(result4[0]["total"]);
});
});
Maybe you can filter the results:
const result5 = result4.filter((result) => result.exitState && result.exitState !== '');
const nbResults = result5.length;
db.tablename.find({},{"exitStates":1}).count()
https://www.w3resource.com/mongodb-exercises/mongodb-exercise-4.php
I can't understand what is your question exactly. if you want to know how many docs exist in the collection and count them by their exitState, this function retuns what you want. I don't know $match works like this or not, But please log the result for test before doing any action on it.
dbo.ProductModel.aggregate([
{ $match: { "EC_TS": { $gte: new Date( start.toISOString() ),
$lte: new Date( end.toISOString() ) } } },
{ $group: {_id: '$exitState', count : {$sum: 1} } }
], (err, result) => {
if (err) throw err;
console.log(result);
// result is like this:
// [ {"_id": "INDIA", "count": 3}, {"_id": "US", "count": 8} ]
});
I'm very new to MongoDB and mongoose and I'd like to get the total number of subscribers from start date to current date by day. In other words, I need to group all my subscribers by day, and for each day I need to sum all of my previous subscribers.
Here are some of my my documents:
{ "_id" : ObjectId("574cef8ee62502d08f34c075"), "userId" : "a7zd609h54wm5kt", "subscribedAt" : ISODate("2016-05-30T18:22:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.098Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c076"), "userId" : "3q2tvd53zcap5mq", "subscribedAt" : ISODate("2016-05-30T19:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.113Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c077"), "userId" : "nvx8mnu1xis5jxt", "subscribedAt" : ISODate("2016-05-28T19:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.117Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c078"), "userId" : "l7eedg616r0zbdf", "subscribedAt" : ISODate("2016-05-28T16:28:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.122Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c079"), "userId" : "9r1wl8ao8bls7g7", "subscribedAt" : ISODate("2016-05-28T11:05:05Z"), "isSubscribed" : false, "createdAt" : ISODate("2016-05-31T01:57:34.125Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07a"), "userId" : "ygwve2e47p7fanl", "subscribedAt" : ISODate("2016-05-29T00:28:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.125Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07b"), "userId" : "1gxspx9jypwc9tu", "subscribedAt" : ISODate("2016-05-29T19:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.127Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07c"), "userId" : "hvy4xjppos8ch2b", "subscribedAt" : ISODate("2016-05-29T01:36:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.127Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07d"), "userId" : "bmpql2d7wkl0jnw", "subscribedAt" : ISODate("2016-05-29T21:50:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.127Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07e"), "userId" : "uir99sy6q3p6i0i", "subscribedAt" : ISODate("2016-05-29T08:22:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.131Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07f"), "userId" : "qmzn3rz308ku017", "subscribedAt" : ISODate("2016-05-29T22:02:05Z"), "isSubscribed" : false, "createdAt" : ISODate("2016-05-31T01:57:34.132Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c080"), "userId" : "ok46sxaf8urrqtj", "subscribedAt" : ISODate("2016-05-29T07:33:05Z"), "isSubscribed" : false, "createdAt" : ISODate("2016-05-31T01:57:34.132Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c081"), "userId" : "ot4nmxqsn4o98vn", "subscribedAt" : ISODate("2016-05-29T23:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.138Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c082"), "userId" : "2voy5ttkk39i1f0", "subscribedAt" : ISODate("2016-05-30T00:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.138Z"), "__v" : 0 }
So I've got 2 subscribers on 2016-05-28, 6 subscribers on 2016-05-29 and 3 subscribers on 2016-05-30,
The result I'm hoping to achieve is something like this
{
"results" : [
{
"date" : ISODate("2016-05-28T00:00:00Z"),
"subscribers" : 2
},
{
"date" : ISODate("2016-05-29T00:00:00Z"),
"subscribers" : 8
},
{
"date" : ISODate("2016-05-30T00:00:00Z"),
"subscribers" : 11
},
]
}
I've tried Aggregation Framework with the following code:
var express = require('express'),
router = express.Router(),
User = require('../models/user');
router.get('/', function(req, res, next) {
User.aggregate([
{
$match: { isSubscribed: true, subscribedAt: {$gte: new Date("2016-05-28T00:00:00+01:00"), $lte: new Date()}}
},
{
$group: {
_id: {$dateToString: { format: "%Y-%m-%d", date: "$subscribedAt" }},
count : { $sum : 1 }
},
},
{
$project: {
_id : 0,
subscribeDate : "$_id",
count : 1
}
},
{
$sort: {subscribeDate: 1}
}
], function(err, result){
if (err) {
console.log("This is an error find the user!")
}
res.render('dashboard', {results: result, title: "Welcome to analytics dashboard!"});
});
});
module.exports = router;
But this only gives me the total subscribers of each day, NOT the the sumup of all the previous subscribers.
{ "count" : 2, "subscribeDate" : "2016-05-28" }
{ "count" : 6, "subscribeDate" : "2016-05-29" }
{ "count" : 3, "subscribeDate" : "2016-05-30" }
I've also tried mapReduce as suggested here with the following code:
var express = require('express'),
router = express.Router(),
User = require('../models/user'),
DailySubscriber = require('../models/dailySubscriber');
router.get('/', function(req, res, next) {
var userObject = {
"query": {isSubscribed: true},
"out": "dailySubscriber"
};
userObject.map = function () {
var date = new Date(this.subscribedAt.valueOf() - (this.subscribedAt.valueOf() % (1000 * 60 * 60 * 24 )));
emit(date, 1)
}
userObject.reduce = function (k, vals) { return vals.length }
User.mapReduce(userObject, function (err, results) {
//console.log(results)
})
var subscriberObject = {
"scope": { "total": 0 },
"finalize": function(key, value) {
total += value;
return total;
},
"out": "totalSubscriber"
};
subscriberObject.map = function () {
emit(this._id, this.value)
}
subscriberObject.reduce = function (k, vals) { return vals.length }
DailySubscriber.mapReduce(subscriberObject, function (err, total) {
console.log("This is the result" + total)
})
res.render('dashboard', {title: "Welcome to analytics dashboard!"});
});
module.exports = router;
This did NOT work when I ran my node app and I got the error This is the result undefined in the console, BUT it did work in MongoDB Shell with the following result which is very close to what I want but still not so ideal, as it always shows _id and value as the key and value.
{
"results" : [
{
"_id" : ISODate("2016-05-28T00:00:00Z"),
"value" : 2
},
{
"_id" : ISODate("2016-05-29T00:00:00Z"),
"value" : 8
},
{
"_id" : ISODate("2016-05-30T00:00:00Z"),
"value" : 11
},
]
}
What would be the best way of doing it? I'm using Node.js, Express and Mongoose, if that helps.
Any help would be much appreciated! Thanks in advance!
imho - having aggregation framework to have a daily sum is best what we can squeeze from mongo. As (from sql world) we don't have CTE, we cannot refer to previous document and that makes some analytics hard.
What I will do in this case is just simple forEach loop and update the sum value creating moving Sum in this particular case. This will require that data need to be sorted from oldest to newest. A sudocode for that below:
var previous = 0;
forEach (var r in result)
{
r.count += previous;
previous = r.count;
}