Add additional properties to the output json - mongodb

There is a collection of User
{
"_id" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"updatedAt" : ISODate("2017-11-16T09:34:14.651Z"),
"createdAt" : ISODate("2017-11-16T08:01:14.119Z"),
"name" : "John",
"email" : "test1#gmail.com",
"groupsFavorite" : [
ObjectId("5a0d45db8af3a91847b7cf96")
],
"groups" : [
ObjectId("5a0d45db8af3a91847b7cf96"),
ObjectId("5a0d45e18af3a91847b7cf97")
],
"__v" : 3
}
There is a collection of Groups
/* 1 */
{
"_id" : ObjectId("5a0d45db8af3a91847b7cf96"),
"updatedAt" : ISODate("2017-11-16T08:01:31.815Z"),
"createdAt" : ISODate("2017-11-16T08:01:31.815Z"),
"userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"title" : "New title",
"slug" : "new-title-1",
"description" : "Lorem",
"__v" : 0
}
/* 2 */
{
"_id" : ObjectId("5a0d45e18af3a91847b7cf97"),
"updatedAt" : ISODate("2017-11-16T08:01:37.005Z"),
"createdAt" : ISODate("2017-11-16T08:01:37.005Z"),
"userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"title" : "New title",
"slug" : "new-title-2",
"description" : "Lorem",
"__v" : 0
}
/* 3 */
{
"_id" : ObjectId("5a0d5cb0cd59342da943d55a"),
"updatedAt" : ISODate("2017-11-16T09:38:56.912Z"),
"createdAt" : ISODate("2017-11-16T09:38:56.912Z"),
"userId" : ObjectId("5a0d5c48cd59342da943d559"),
"title" : "New title",
"slug" : "new-title-3",
"description" : "Lorem",
"__v" : 0
}
There is a method that returns groups of a particular user.
It is necessary to add these data to the new property of favorite: true or false for building a table.
For example:
{
"_id" :"5a0d45db8af3a91847b7cf96",
"updatedAt" : "2017-11-16T08:01:31.815Z",
"createdAt" : "2017-11-16T08:01:31.815Z",
"userId" : "5a0d45ca8af3a91847b7cf95",
"title" : "New title",
"slug" : "new-title-1",
"description" : "Lorem",
"favorite": "true"
},
{
"_id" : "5a0d45e18af3a91847b7cf97",
"updatedAt" : "2017-11-16T08:01:37.005Z",
"createdAt" : "2017-11-16T08:01:37.005Z",
"userId" : "5a0d45ca8af3a91847b7cf95",
"title" : "New title",
"slug" : "new-title-2",
"description" : "Lorem",
"favorite": "false"
},
{
"_id" : "5a0d5cb0cd59342da943d55a",
"updatedAt" : "2017-11-16T09:38:56.912Z",
"createdAt" : "2017-11-16T09:38:56.912Z",
"userId" : "5a0d5c48cd59342da943d559",
"title" : "New title",
"slug" : "new-title-3",
"description" : "Lorem",
"favorite": "false"
}

You can use $lookup operator for checking the _id and userId fields in "User" collection. And also for determining it is in or not, you can use $eq operator.
db.getCollection('Groups').aggregate([
{
$lookup:
{
from: "User",
localField: "_id",
foreignField: "groupsFavorite",
as: "FavoriteByGrp"
}
}
,{
$lookup:
{
from: "User",
localField: "userId",
foreignField: "_id",
as: "FavoriteByUsr"
}
}
,{
"$project":
{
_id:1,
updatedAt:1,
createdAt:1,
userId:1,
title:1,
slug:1,
description:1,
favorite:
{
"$cond":
{
if: { "$eq": [ "$FavoriteByGrp._id", "$FavoriteByUsr._id" ] },
then: "true",
else: "false"
}
}
}
}
])
Result:
/* 1 */
{
"_id" : ObjectId("5a0d45db8af3a91847b7cf96"),
"updatedAt" : ISODate("2017-11-16T08:01:31.815Z"),
"createdAt" : ISODate("2017-11-16T08:01:31.815Z"),
"userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"title" : "New title",
"slug" : "new-title-1",
"description" : "Lorem",
"favorite" : "true"
}
/* 2 */
{
"_id" : ObjectId("5a0d45e18af3a91847b7cf97"),
"updatedAt" : ISODate("2017-11-16T08:01:37.005Z"),
"createdAt" : ISODate("2017-11-16T08:01:37.005Z"),
"userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"title" : "New title",
"slug" : "new-title-2",
"description" : "Lorem",
"favorite" : "false"
}
/* 3 */
{
"_id" : ObjectId("5a0d5cb0cd59342da943d55a"),
"updatedAt" : ISODate("2017-11-16T09:38:56.912Z"),
"createdAt" : ISODate("2017-11-16T09:38:56.912Z"),
"userId" : ObjectId("5a0d5c48cd59342da943d559"),
"title" : "New title",
"slug" : "new-title-3",
"description" : "Lorem",
"favorite" : "false"
}

Related

How to find and update an array in the object of array document using mongoose

A query to how to update the items array of object by
finding the breed dachshund
update the name to new-dog
updatedAt to the current time
[{
"_id" : ObjectId("60053b74aa72f132cb75b8b6"),
"clientId" : "test",
"items" : [
{
"_id" : ObjectId("60053b74aa72f132cb75b8b7"),
"name" : "tommy",
"breed" : "dachshund",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
},
{
"_id" : ObjectId("60053b74aa72f132cb75b8b8"),
"name" : "mickey",
"breed" : "husky",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
},
{
"_id" : ObjectId("60053b74aa72f132cb75b8b9"),
"name" : "whiskey",
"breed" : "dachshund",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
},
{
"_id" : ObjectId("60053b74aa72f132cb75b8ba"),
"name" : "milo",
"breed" : "bulldog",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
},
{
"_id" : ObjectId("60053b74aa72f132cb75b8bb"),
"name" : "pooh",
"breed" : "poodle",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
}
],
"shopname" : "myshopify"
}]
const curDatetime = moment(moment();
model.updateOne(
{_id: ObjectId("60053b74aa72f132cb75b8b6")},
{
arrayFilters: [
{'el.breed': 'dachshund'}
]
},
{
$set: {
'items.$[el].name': 'new-dog',
'items.$[el].updatedAt': curDatetime
}
}, "multi": true)

MongoDB project with lookup

I want to get other collection's field using $lookup.
For example, this is my users collection:
{ "_id" : ObjectId("601c4f89049f9d2cc47eece2"), "username" : "Ahmad", "email" : "aaa#aaa.com", "password" : "$2a$08$fAT1G.db9LjXRV7bOPKNzuosWZ3QGJs2rdHIGmPbWtusDA0Qko47e", "tokens" : [ { "_id" : ObjectId("601d4de52472f01ef4552e77"), "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwMWM0Zjg5MDQ5ZjlkMmNjNDdlZWNlMiIsImlhdCI6MTYxMjUzMzIyMSwiZXhwIjoxNjEzMTM4MDIxfQ.lEt5mIQkjVCRFvDJsHoK1rwdN-WELSVWMFW3p8itZBU" }, { "_id" : ObjectId("601c4f89049f9d2cc47eece3"), "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwMWM0Zjg5MDQ5ZjlkMmNjNDdlZWNlMiIsImlhdCI6MTYxMjQ2ODEwNSwiZXhwIjoxNjEzMDcyOTA1fQ.WwKCenn7Qh3C1DhJT7H1Kcqu4ZRl0Z7SYJxBV6v87S8" } ], "createdAt" : ISODate("2021-02-04T19:48:25.024Z"),
"updatedAt" : ISODate("2021-02-05T13:53:41.730Z"), "__v" : 0 }
{ "_id" : ObjectId("601c954a59477b1d38e8a69e"), "username" : "fred", "email" : "isded#gmail.com", "password" : "$2a$08$nZ2kusIoSdwgjBpcZX4WTe2sO3tnieUcVIDGXiUCofLSvkdSdTRFa", "tokens" : [ { "_id" : ObjectId("601c954a59477b1d38e8a69f"), "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwMWM5NTRhNTk0NzdiMWQzOGU4YTY5ZSIsImlhdCI6MTYxMjQ4NTk2MiwiZXhwIjoxNjEzMDkwNzYyfQ.bHkhfBlgswerB25za2y3YODk-cbRgGhlcrtr-zaIG9M" } ], "createdAt" : ISODate("2021-02-05T00:46:02.518Z"), "updatedAt" : ISODate("2021-02-05T00:46:02.518Z"), "__v" : 0 }
And here posts collection:
{ "_id" : ObjectId("601c5190939a1e294c688267"), "title" : "abdulila", "content" : "wqd", "category" : "Health", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "comments" : [ {
"_id" : ObjectId("601c532a5b746f1ad081c57e"), "content" : "Marchgisio", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "createdAt" : ISODate("2021-02-04T20:03:54.055Z"), "updatedAt" : ISODate("2021-02-04T20:03:54.055Z") }, { "_id" : ObjectId("601c53445b746f1ad081c57f"), "content" : "Balotelli", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "createdAt" : ISODate("2021-02-04T20:04:20.967Z"), "updatedAt" : ISODate("2021-02-04T20:04:20.967Z") } ], "createdAt" : ISODate("2021-02-04T19:57:04.902Z"), "updatedAt" : ISODate("2021-02-04T20:04:20.968Z"), "__v" : 2 }
{ "_id" : ObjectId("601c958259477b1d38e8a6a0"), "title" : "ohh mighty spurs", "content" : "harry kane", "category" : "Sports", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "comments" : [ { "_id" : ObjectId("601c958f59477b1d38e8a6a1"), "content" : "eorje", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "createdAt" : ISODate("2021-02-05T00:47:11.461Z"), "updatedAt" : ISODate("2021-02-05T00:47:11.461Z") }, { "_id" : ObjectId("601c95cac3b0131328e29344"), "content" : "qwe", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "createdAt" : ISODate("2021-02-05T00:48:10.207Z"), "updatedAt" : ISODate("2021-02-05T00:48:10.207Z") }, { "_id" : ObjectId("601c95e3af31ab1608abd23f"), "content" : "wef", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "createdAt" : ISODate("2021-02-05T00:48:35.168Z"), "updatedAt" : ISODate("2021-02-05T00:48:35.168Z") } ], "createdAt" : ISODate("2021-02-05T00:46:58.962Z"), "updatedAt" : ISODate("2021-02-05T00:48:35.168Z"), "__v" : 3 }
{ "_id" : ObjectId("601d210fbf41fd262c9172c4"), "title" : "bobo", "content" : "hiv is a lie and in god name we will kill all the jews in balastin XD UwU\n", "category" : "Movies", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "comments" : [ ], "createdAt" : ISODate("2021-02-05T10:42:23.773Z"), "updatedAt" : ISODate("2021-02-05T10:42:23.773Z"), "__v"
: 0 }
{ "_id" : ObjectId("601d4a2f1f169d3d9cbfcbfe"), "title" : "Abdallah", "content" : "dfsv", "category" : "Health", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "comments" : [ { "_id" : ObjectId("601d50d80678f626105f943e"), "content" : "dvd", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "createdAt" : ISODate("2021-02-05T14:06:16.941Z"), "updatedAt"
: ISODate("2021-02-05T14:06:16.941Z") }, { "_id" : ObjectId("601d531fcc80c13fb832af40"), "content" : "svsf", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "createdAt" : ISODate("2021-02-05T14:15:59.873Z"), "updatedAt" : ISODate("2021-02-05T14:15:59.873Z") } ], "createdAt" : ISODate("2021-02-05T13:37:51.787Z"), "updatedAt" : ISODate("2021-02-05T14:15:59.874Z"), "__v" : 2 }
My purpose is to get all comments of 1 specific post. Then, for each comment - I want its content and owner username.
This is my try:
Post.aggregate([
{
$match: { _id: mongoose.Types.ObjectId(req.query.postID) },
},
{
$limit: 1,
},
{
$project: {
_id: 0,
'comments.owner': 1,
'comments.content': 1,
},
},
]);
So this gives me back the content and the owner id. But I want the owner username which presents in the users collection. How could I achieve this?
I came up with this pipeline. I'm sure it cloud be improve.
The steps are (commented in the pipeline)
Split comments array so we could concentrate on each one
Lookup for the user info
The lookup brings an array of one element, so I unwind it.
Replace the owner object id with the owner username.
Group comments
Project the needed fields
I test this directly on mongodb with one of your post.
[
{
$match: { _id: ObjectId("601d4a2f1f169d3d9cbfcbfe") },
},
{
$unwind: '$comments' //split comments array so we could concentrate on each one
},
{
$lookup: {
from: 'user',
localField: 'comments.owner', // lookup for the user info
foreignField: '_id',
as: 'owner'
}
},
{
$unwind: '$owner' // the lookup brings an array of one element, so I unwind it.
},
{
$addFields: {
'comments.owner': "$owner.username" //replace the owner object id with the owner username
}
},
{
$group: {
_id: '_id', // group comments
'comments': {$push: '$comments'}
}
},
{
$project:{
_id: 0, // project the needed fields
'comments.content':1,
'comments.owner': 1,
}
}
])

MongoDB : lookup exact match without false rows

I have 3 tables :
accounts:[
{id:111,name:'john'},
{id:222,name:'due'}
]
workoutTypes:[
{id:1,title:'a'},
{id:2,title:'b'}
]
accountrecords:[
{_id:10,workoutTypeId:1,accountId:111},
{_id:11,workoutTypeId:1,accountId:222}
]
I used this command to group all account records by workout type that match to the current account like that:
db.workoutTypes.aggregate([
{
$lookup: {
from: "accountrecords",
localField: "_id",
foreignField: "workoutTypeId",
as: "records"
}
},
{
$match: {
$and: [
{ "records": { $ne: [] } },
{ "records.accountId": { $eq: mongoose.Types.ObjectId(accountId) } },
]
}
},
])
the issue that I'm getting the records that related to both of accounts.
saw that eq command return a false value for non-match values.
there is an option to get only the record that matches to current account?
First of all your localField on workoutTypes collection must be id, not _id. Probably a typo from your side. Secondly, you need to use $redact operator if you want to restrict the content. $match actually works as expected, but it actually isn't checking whether all your sub documents are satisfying the criteria.
Update:
Try this query:
db.workoutTypes.aggregate([
{
$lookup: {
from: "accountrecords",
localField: "_id",
foreignField: "workoutTypeId",
as: "records"
}
},
{$match:{"records.accountId":{$exists:true}, "records.accountId":{$eq:ObjectId("5a604b18280420c03e8d3a23")}}},
{$redact:{
$cond:{
if:{$or:[{$eq:["$accountId",ObjectId("5a604b18280420c03e8d3a23")]},{$not:"$accountId"}]},
then:"$$DESCEND",
else:"$$PRUNE"
}
}}
])
And the output is:
/* 1 */
{
"_id" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"updatedAt" : ISODate("2018-04-07T11:59:52.583Z"),
"createdAt" : ISODate("2018-04-07T11:59:52.583Z"),
"title" : "Snatch",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5acb1b666b08493b30deed92"),
"updatedAt" : ISODate("2018-04-09T07:51:02.294Z"),
"createdAt" : ISODate("2018-04-09T07:51:02.294Z"),
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"repetition" : 4,
"weight" : 120,
"__v" : 0
},
{
"_id" : ObjectId("5acb1b6f6b08493b30deed93"),
"updatedAt" : ISODate("2018-04-09T07:51:11.878Z"),
"createdAt" : ISODate("2018-04-09T07:51:11.878Z"),
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"repetition" : 5,
"weight" : 130,
"__v" : 0
},
{
"_id" : ObjectId("5ace23aa1c4d590dc049e94e"),
"updatedAt" : ISODate("2018-04-11T15:03:06.824Z"),
"createdAt" : ISODate("2018-04-11T15:03:06.824Z"),
"repetition" : 124,
"weight" : 32,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"__v" : 0
},
{
"_id" : ObjectId("5ace23b21c4d590dc049e94f"),
"updatedAt" : ISODate("2018-04-11T15:03:14.293Z"),
"createdAt" : ISODate("2018-04-11T15:03:14.293Z"),
"repetition" : 325,
"weight" : 235,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"__v" : 0
},
{
"_id" : ObjectId("5acc8ef5345125417cca18e3"),
"updatedAt" : ISODate("2018-04-10T10:16:21.709Z"),
"createdAt" : ISODate("2018-04-10T10:16:21.709Z"),
"repetition" : 123,
"weight" : 456,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"__v" : 0
}
]
}
/* 2 */
{
"_id" : ObjectId("5acdf56afd5ca008d01b706f"),
"updatedAt" : ISODate("2018-04-11T11:45:46.192Z"),
"createdAt" : ISODate("2018-04-11T11:45:46.192Z"),
"title" : "Jerk",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5acdf597fd5ca008d01b7070"),
"updatedAt" : ISODate("2018-04-11T11:46:31.674Z"),
"createdAt" : ISODate("2018-04-11T11:46:31.674Z"),
"repetition" : 12,
"weight" : 100,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5acdf56afd5ca008d01b706f"),
"__v" : 0
}
]
}
/* 3 */
{
"_id" : ObjectId("5ace336ed36c780e6ce76d5d"),
"updatedAt" : ISODate("2018-04-11T16:10:22.483Z"),
"createdAt" : ISODate("2018-04-11T16:10:22.483Z"),
"title" : "Weight lifting",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5ace337ed36c780e6ce76d5e"),
"updatedAt" : ISODate("2018-04-11T16:10:38.708Z"),
"createdAt" : ISODate("2018-04-11T16:10:38.708Z"),
"repetition" : 21,
"weight" : 100,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ace336ed36c780e6ce76d5d"),
"__v" : 0
}
]
}
/* 4 */
{
"_id" : ObjectId("5ac8cf5ef14469169d8627e8"),
"updatedAt" : ISODate("2018-04-07T14:02:06.155Z"),
"createdAt" : ISODate("2018-04-07T14:02:06.155Z"),
"title" : "Double under",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5acc8f11345125417cca18e4"),
"updatedAt" : ISODate("2018-04-10T10:16:49.069Z"),
"createdAt" : ISODate("2018-04-10T10:16:49.069Z"),
"repetition" : 111111,
"weight" : 222222,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8cf5ef14469169d8627e8"),
"__v" : 0
},
{
"_id" : ObjectId("5ace2d7b1c4d590dc049e950"),
"updatedAt" : ISODate("2018-04-11T15:44:59.722Z"),
"createdAt" : ISODate("2018-04-11T15:44:59.722Z"),
"weight" : 23,
"repetition" : 123555555,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8cf5ef14469169d8627e8"),
"__v" : 0
}
]
}
/* 5 */
{
"_id" : ObjectId("5ac8cfdd79a48216b3e048b0"),
"updatedAt" : ISODate("2018-04-07T14:04:13.670Z"),
"createdAt" : ISODate("2018-04-07T14:04:13.670Z"),
"title" : "Push-ups",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5accc1f1cd58a407c6562f79"),
"updatedAt" : ISODate("2018-04-10T13:53:53.933Z"),
"createdAt" : ISODate("2018-04-10T13:53:53.933Z"),
"repetition" : 123,
"weight" : 456000,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8cfdd79a48216b3e048b0"),
"__v" : 0
}
]
}
Now you just replace ObjectId("5a604b18280420c03e8d3a23") in the query with your mongoose code mongoose.Types.ObjectId(accountId) and you should be good now.

Need Help Join Collection

Collection Inventory sample data:
{
"_id" : "89011704252315531324",
"sku" : "A2015-01-000",
"type" : "package",
"status" : "active",
"lng" : "-72.789153",
"lat" : "44.173515",
"acq" : "28",
"gtime" : ISODate("2017-01-11T22:27:48.000Z"),
"qlng" : "-72.796501",
"qlat" : "44.214783",
"qtime" : ISODate("2016-11-27T18:21:10.000Z"),
"timestamp" : ISODate("2017-01-12T14:43:29.000Z"),
"modified" : Date(-62135596800000),
"battery" : "60",
"wearables" : [
{
"_id" : "0009003C100228234E45",
"type" : "wearable",
"status" : "active",
"battery" : "50",
"timestamp" : ISODate("2017-01-12T11:43:33.000Z")
},
{
"_id" : "004A003F200B36634E45",
"type" : "cradle",
"status" : "active",
"battery" : "64",
"timestamp" : ISODate("2017-01-11T22:27:26.000Z")
},
{
"_id" : "11223344556600000B55",
"type" : "falldetect",
"status" : "active",
"battery" : "64",
"timestamp" : ISODate("2017-01-12T08:43:29.000Z")
}
],
"company" : "ConnectAmericaProduction",
"companies" : [],
"remoteIp" : "172.31.45.196:53864",
"subscriber" : "5783e20aa2c89f346e000006",
"ring" : "90",
"speaker" : "90",
"mic" : "55",
"version" : "4352",
"cradle" : "OFF",
"ctime" : ISODate("2017-01-11T23:13:59.000Z"),
"csqtime" : Date(-62135596800000)
}
collection calllog sample data
{
"_id" : "89011704252315531324",
"cdr" : [
{
"direction" : "Outgoing",
"duration" : 46,
"timestamp" : ISODate("2016-11-23T03:25:06.000Z"),
"number" : "",
"name" : "Call Center",
"lng" : "-71.208061",
"lat" : "42.330265",
"acq" : "",
"timezone" : {
"dstOffset" : 0.0,
"rawOffset" : 0.0,
"status" : "",
"timeZoneId" : "",
"timeZoneName" : ""
}
},
{
"direction" : "Incoming",
"duration" : 51,
"timestamp" : ISODate("2016-11-23T03:26:02.000Z"),
"number" : "",
"name" : "Call Center",
"lng" : "-71.205727",
"lat" : "42.333347",
"acq" : "",
"timezone" : {
"dstOffset" : 0.0,
"rawOffset" : 0.0,
"status" : "",
"timeZoneId" : "",
"timeZoneName" : ""
}
},
{
"direction" : "Outgoing",
"duration" : 49,
"timestamp" : ISODate("2016-11-27T18:21:04.000Z"),
"number" : "",
"name" : "Call Center",
"lng" : "-72.796501",
"lat" : "44.214783",
"acq" : "",
"timezone" : {
"dstOffset" : 0.0,
"rawOffset" : -18000.0,
"status" : "OK",
"timeZoneId" : "America/New_York",
"timeZoneName" : "Eastern Standard Time"
}
}
]
}
after run this aggrgrate function
db.calllog.aggregate([{$unwind: "$cdr"}, {$lookup:{from: "inventory", localField: "_id", foreignField: "_id", as: "wearables" }}, { "$project": { "cdr.direction": 1, "cdr.duration": 1,"cdr.date": 1,"wearables.type": 1, "wearables.status": 1, "wearables.battery": 1} }])
Result:
{ "_id" : "89011704252315531324", "cdr" : { "direction" : "Outgoing", "duration" : 46 }, "wearables" : [ { "type" : "package", "status" : "active", "battery" : "60" } ] }
{ "_id" : "89011704252315531324", "cdr" : { "direction" : "Incoming", "duration" : 51 }, "wearables" : [ { "type" : "package", "status" : "active", "battery" : "60" } ] }
{ "_id" : "89011704252315531324", "cdr" : { "direction" : "Outgoing", "duration" : 49 }, "wearables" : [ { "type" : "package", "status" : "active", "battery" : "60" } ] }
needed help can not get query to shows wearables type such as wearable, cradle, falldetect
thank
Did you try to do wearables.wearables.type? When you call wearables.type, you are actually getting the type of the Inventory. If you need the type of the wearable that is inside the inventory. You need to put inventory.wearables.type. The initial problem is that you're calling the inventory "wearables" and making a confusion out of it.
I would do the following:
db.calllog.aggregate([{$unwind: "$cdr"},
{$lookup:{from: "inventory", localField: "_id", foreignField: "_id", as: "inventory" }},
{$unwind: "$inventory.wearables"},
{ "$project": {
"cdr.direction": 1,
"cdr.duration": 1,
"cdr.date": 1,
"inventory.type": 1,
"inventory.status": 1,
"inventory.battery": 1,
"inventory.wearables.type":1
}}])

How to use MongoDB $group stage to both group and count repeated values?

I am having trouble with the $group stage in my aggregation. I want to group all the "recentPlays.quiz" values together and count the repeated values, so the end result I want from the aggregation is two fields: the quiz object and the total. In this case it would be something like:
{
"recentPlays" : [
{
"quiz" : {
"author" : "red-tester1",
"title" : "Asdffff Dfasdf"
},
"count": 1
},
{
"quiz" : {
"author" : "red-tester3",
"title" : "Creation Test 2"
},
"count": 1
},
{
"quiz" : {
"author" : "blue-tester1",
"title" : "Finky Fink"
},
"count": 4
}
]
}
Here is the aggregation I have so far:
db.users.aggregate([
{$match: { "recentPlays.date": {$gte:twentyFourHrsAgo}}},
{$project: {"recentPlays.quiz":1, _id:0}}
]).pretty();
Here is that aggregation's output:
MongoDB shell version: 3.2.1
connecting to: videoQuiz
{
"recentPlays" : [
{
"quiz" : {
"author" : "red-tester1",
"title" : "Asdffff Dfasdf"
}
},
{
"quiz" : {
"author" : "red-tester3",
"title" : "Creation Test 2"
}
},
{
"quiz" : {
"author" : "blue-tester1",
"title" : "Finky Fink"
}
},
{
"quiz" : {
"author" : "blue-tester1",
"title" : "Finky Fink"
}
},
{
"quiz" : {
"author" : "blue-tester1",
"title" : "Finky Fink"
}
},
{
"quiz" : {
"author" : "blue-tester1",
"title" : "Finky Fink"
}
}
]
}
Here is the entire collection:
MongoDB shell version: 3.2.1
connecting to: videoQuiz
{
"_id" : ObjectId("580f7be62c6fd3c8065577f5"),
"user" : "blue-tester1",
"email" : "aslfjjcc#lkcjasdc.com",
"createdAt" : ISODate("2016-10-25T15:36:06.933Z"),
"recentPlays" : [
{
"quiz" : {
"author" : "red-tester1",
"title" : "Asdffff Dfasdf"
},
"score" : "0",
"date" : ISODate("2016-10-25T15:36:27.546Z")
},
{
"quiz" : {
"author" : "red-tester3",
"title" : "Creation Test 2"
},
"score" : "100",
"date" : ISODate("2016-10-25T15:37:09.142Z")
}
],
"mostRecentQuiz" : {
"author" : "red-tester3",
"title" : "Creation Test 2"
},
"mostRecentQuizTime" : ISODate("2016-10-25T15:37:09.142Z"),
"plays" : 2
}
{
"_id" : ObjectId("580a5dea650296d808082e65"),
"user" : "red-tester3",
"email" : "aldkdk#ccc.com",
"createdAt" : ISODate("2016-10-21T18:26:50.870Z"),
"recentPlays" : [
{
"quiz" : {
"author" : "red-tester2",
"title" : "TOP PLAYED QUIZ - Today"
},
"score" : "0",
"date" : ISODate("2016-10-21T18:27:16.292Z")
},
{
"quiz" : {
"author" : "red-tester2",
"title" : "TOP LIKED QUIZ - TODAY"
},
"score" : "100",
"date" : ISODate("2016-10-21T18:27:32.788Z")
},
{
"quiz" : {
"author" : "red-tester2",
"title" : "TOP LIKED QUIZ - TODAY"
},
"score" : "100",
"date" : ISODate("2016-10-21T18:27:44.497Z")
},
{
"quiz" : {
"author" : "Bertram",
"title" : "frfrf"
},
"score" : "100",
"date" : ISODate("2016-10-21T18:28:43.893Z")
},
{
"quiz" : {
"author" : "Bertram",
"title" : "Here We Go With the New Thing"
},
"score" : "0",
"date" : ISODate("2016-10-21T18:43:51.205Z")
},
{
"quiz" : {
"author" : "red-tester3",
"title" : "Presidents of the United States"
},
"score" : "0",
"date" : ISODate("2016-10-23T00:53:29.167Z")
},
{
"quiz" : {
"author" : "red-tester3",
"title" : "Presidents of the United States"
},
"score" : "0",
"date" : ISODate("2016-10-23T00:53:44.815Z")
},
{
"quiz" : {
"author" : "red-tester3",
"title" : "Creation Test 1"
},
"score" : "100",
"date" : ISODate("2016-10-23T23:50:55.355Z")
},
{
"quiz" : {
"author" : "red-tester3",
"title" : "Creation Test 2"
},
"score" : "100",
"date" : ISODate("2016-10-23T23:52:33.210Z")
},
{
"quiz" : {
"author" : "red-tester3",
"title" : "Here Is a New Title"
},
"score" : "100",
"date" : ISODate("2016-10-23T23:58:53.683Z")
}
],
"mostRecentQuiz" : {
"author" : "red-tester3",
"title" : "Here Is a New Title"
},
"mostRecentQuizTime" : ISODate("2016-10-23T23:58:53.683Z"),
"plays" : 10,
"likedQuizzes" : [
{
"title" : "TOP LIKED QUIZ - TODAY",
"author" : "red-tester2",
"date" : ISODate("2016-10-21T18:27:34.893Z")
},
{
"title" : "frfrf",
"author" : "Bertram",
"date" : ISODate("2016-10-21T18:28:45.863Z")
},
{
"title" : "Here We Go With the New Thing",
"author" : "Bertram",
"date" : ISODate("2016-10-21T18:43:53.148Z")
}
],
"createdQuizzes" : [
{
"title" : "Yeah Here We Go",
"id" : ObjectId("580a63f274b9a89c061f973e")
},
{
"title" : "Z Alpha",
"id" : ObjectId("580a641474b9a89c061f973f")
},
{
"title" : "Tags Limit Test",
"id" : ObjectId("580a6bda8d8049ac0bc1df2e")
},
{
"title" : "Tags Limit test2",
"id" : ObjectId("580a6bf98d8049ac0bc1df2f")
},
{
"title" : "Presidents of the United States",
"id" : ObjectId("580c09d28d8049ac0bc1df30")
},
{
"title" : "Creation Test 1",
"id" : ObjectId("580d4cca8d8049ac0bc1df31")
},
{
"title" : "Creation Test 2",
"id" : ObjectId("580d4d2d8d8049ac0bc1df32")
},
{
"title" : "Here Is a New Title",
"id" : ObjectId("580d4ead8d8049ac0bc1df33")
}
]
}
Thanks in advance for any guidance. Please excuse the dummy text in these documents, it is for testing purposes only.
This will be a two step process. The first step is to $unwind the "recentPlays" array. The second step is to $group by "recentPlays.quiz".
For example:
db.users.aggregate([
{ "$match" : { "recentPlays.date": { "$gte" : twentyFourHrsAgo}}},
{ "$project" : {"recentPlays.quiz":1, _id:0}},
{ "$unwind" : "$recentPlays" },
{ "$group" : { "_id" : "$recentPlays.quiz", "total" : { "$sum" : 1 } } }
]).pretty();