get length of array via variable just created mongodb - mongodb

I am new to mongodb, I have a dataset that looks like the following, and I'm trying to Write an aggregation query that will determine the number of unique companies with which an individual has been associated.
Schema:
{
"_id" : ObjectId("52cdef7c4bab8bd675297d8b"),
"name" : "AdventNet",
"permalink" : "abc3",
"crunchbase_url" : "http://www.crunchbase.com/company/adventnet",
"homepage_url" : "http://adventnet.com",
"blog_url" : "",
"blog_feed_url" : "",
"twitter_username" : "manageengine",
"category_code" : "enterprise",
"number_of_employees" : 600,
"founded_year" : 1996,
"deadpooled_year" : 2,
"tag_list" : "",
"alias_list" : "Zoho ManageEngine ",
"email_address" : "pr#adventnet.com",
"phone_number" : "925-924-9500",
"description" : "Server Management Software",
"created_at" : ISODate("2007-05-25T19:24:22Z"),
"updated_at" : "Wed Oct 31 18:26:09 UTC 2012",
"overview" : "<p>AdventNet is now Zoho ManageEngine.</p>\n\n<p>Founded in 1996, AdventNet has served a diverse range of enterprise IT, networking and telecom customers.</p>\n\n<p>AdventNet supplies server and network management software.</p>",
"image" : {
"available_sizes" : [
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-150x150.png"
],
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-250x250.png"
],
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-450x450.png"
]
]
},
"products" : [ ],
"relationships" : [
{
"is_past" : true,
"title" : "CEO and Co-Founder",
"person" : {
"first_name" : "Sridhar",
"last_name" : "Vembu",
"permalink" : "sridhar-vembu"
}
},
{
"is_past" : true,
"title" : "VP of Business Dev",
"person" : {
"first_name" : "Neil",
"last_name" : "Butani",
"permalink" : "neil-butani"
}
},
{
"is_past" : true,
"title" : "Usabiliy Engineer",
"person" : {
"first_name" : "Bharath",
"last_name" : "Balasubramanian",
"permalink" : "bharath-balasibramanian"
}
},
{
"is_past" : true,
"title" : "Director of Engineering",
"person" : {
"first_name" : "Rajendran",
"last_name" : "Dandapani",
"permalink" : "rajendran-dandapani"
}
},
{
"is_past" : true,
"title" : "Market Analyst",
"person" : {
"first_name" : "Aravind",
"last_name" : "Natarajan",
"permalink" : "aravind-natarajan"
}
},
{
"is_past" : true,
"title" : "Director of Product Management",
"person" : {
"first_name" : "Hyther",
"last_name" : "Nizam",
"permalink" : "hyther-nizam"
}
},
{
"is_past" : true,
"title" : "Western Regional OEM Sales Manager",
"person" : {
"first_name" : "Ian",
"last_name" : "Wenig",
"permalink" : "ian-wenig"
}
}
],
"competitions" : [ ],
"providerships" : [
{
"title" : "DHFH",
"is_past" : true,
"provider" : {
"name" : "A Small Orange",
"permalink" : "a-small-orange"
}
}
],
"total_money_raised" : "$0",
"funding_rounds" : [ ],
"investments" : [ ],
"acquisition" : null,
"acquisitions" : [ ],
"offices" : [
{
"description" : "Headquarters",
"address1" : "4900 Hopyard Rd.",
"address2" : "Suite 310",
"zip_code" : "94588",
"city" : "Pleasanton",
"state_code" : "CA",
"country_code" : "USA",
"latitude" : 37.692934,
"longitude" : -121.904945
}
],
"milestones" : [ ],
"video_embeds" : [ ],
"screenshots" : [
{
"available_sizes" : [
[
[
150,
94
],
"assets/images/resized/0004/3400/43400v1-max-150x150.png"
],
[
[
250,
156
],
"assets/images/resized/0004/3400/43400v1-max-250x250.png"
],
[
[
450,
282
],
"assets/images/resized/0004/3400/43400v1-max-450x450.png"
]
],
"attribution" : null
}
],
"external_links" : [ ],
"partners" : [ ]
}
Here is the query I tried:
db.companies.aggregate([{
$match: {
"relationships.person": {
$ne: null
}
}
}, {
$project: {
relationships: 1,
_id: 0
}
}, {
$unwind: "$relationships"
}, {
$group: {
_id: "$relationships.person",
count: {
$addToSet: "$relationships"
}
}
}])
I think I now need to get the length of the $relationships array? How would I do that?

When you only want the size of the array you really don't need to unwind...
Just use $size.
Alter your aggregation to:
db.companies.aggregate([{
$match: {
"relationships.person": {
$ne: null
}
}
}, {
$project: {
relationships: 1,
_id: 0,
relationship_size : { $size : "$relationships"}
}
}
}])
This should give you the result you want
From the comment i understand you want some more logic in the aggregation, from outta my head i would alter your aggregation to:
db.companies.aggregate([{
$match: {
"relationships.person": {
$ne: null
}
}
}, {
$project: {
relationships: 1,
_id: 0
}
}, {
$unwind: "$relationships"
}, {
$group: {
_id: "$relationships.person.permalink",
count : {$sum : 1}
}
}])
I can't find a "company name" in your relationships array so i use the permalink property

Related

Requests in mongodb

I have three objects. I am trying to fing the parents who haven't got a job. I am writing this code:
db.getCollection('students').find({
'parents.profession':{$exists: false}
})
I have no mistakes, but it is loking for me users who haven't got a parents. What am i doing wrong
My Objects:
{
"_id" : ObjectId("60c1bd314ed90f98fbbf9d5b"),
"name" : "Ivan",
"class" : 2.0,
"lessons" : [
"basic"
],
"avgScore" : 4.2,
"parents" : [
{
"gender" : "male",
"name" : "Ivan",
"profession" : "trainer"
},
{
"gender" : "female",
"name" : "Vika"
}
]
}
{
"_id" : ObjectId("60c1bd314ed90f98fbbf9d5d"),
"name" : "Kostya",
"class" : 2.0,
"lessons" : [
"basic"
],
"avgScore" : 4.24,
"parents" : [
{
"gender" : "male",
"name" : "Ivan",
"profession" : "blogger"
},
{
"gender" : "male",
"name" : "Andriy",
"profession" : "blogger"
}
]
}
Use $elemMatch:
db.collection.find({
"parents": {
"$elemMatch": {
profession: {
$exists: false
}
}
}
})
Here is the working example: https://mongoplayground.net/p/XT8JJdZ9L5H

$map upto three nested array mongodb aggregation

I´m facing a challenge here. I have this collection here
{
"_id" : ObjectId("5e0ff6d424f9fc12bc3d9464"),
"name" : "Pizzaria Don Juan",
"active" : true,
"branches" : [
{
"location" : {
"type" : "Point",
"coordinates" : [ ]
},
"_id" : ObjectId("5e19cafc31d60216b8dbd649"),
"name" : "Parque da Mooca",
"address" : "Rua Dianópolis",
"addressNumber" : 1283,
"federalId" : "10.445.089/0001-44",
"complement" : "Ap 55",
"postalCode" : "03126-007",
"coveredArea" : 0,
"neighborhood" : "Parque da Mooca",
"deliveryTime" : 0,
"deliveryRate" : 0,
"standard" : false,
"city" : "Mococa",
"state" : "RJ",
"emails" : [ ],
"phones" : [ ],
"daysWeek" : [ ],
"socialMedias" : [ ],
"paymentTerms" : [ ],
"sections" : [ ]
},
{
"location" : {
"type" : "Point",
"coordinates" : [ ]
},
"_id" : ObjectId("5e19c9a531d60216b8dbd639"),
"name" : "Principal",
"address" : "Rua Nicolau Filizola",
"addressNumber" : null,
"federalId" : "10.445.089/0001-53",
"complement" : "",
"postalCode" : "05547-010",
"coveredArea" : 0,
"neighborhood" : "Jardim Rosa Maria",
"deliveryTime" : 0,
"deliveryRate" : 0,
"standard" : true,
"city" : "São Paulo",
"state" : "SP",
"emails" : [
{
"_id" : ObjectId("5e19ca9531d60216b8dbd643"),
"name" : "Contato",
"address" : "contato#pizzariadonjuan.com.br"
},
{
"_id" : ObjectId("5e19ca9531d60216b8dbd642"),
"name" : "Contato2",
"address" : "contato2#pizzariadonjuan.com.br"
}
],
"phones" : [
{
"_id" : ObjectId("5e19ca9531d60216b8dbd645"),
"name" : "Principal",
"number" : "(11) 99740-2216"
},
{
"_id" : ObjectId("5e19ca9531d60216b8dbd644"),
"name" : "Secundario",
"number" : "(11) 2562-2759"
}
],
"daysWeek" : [
{
"_id" : ObjectId("5e1cf99741c52d4a587a9162"),
"startsAt" : 64800000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a124a17fd054900a1afb2")
},
{
"_id" : ObjectId("5e1cf99741c52d4a587a9161"),
"startsAt" : 0,
"endsAt" : 0,
"opens" : false,
"dayWeekId" : ObjectId("5e1a126817fd054900a1afb3")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a9170"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a126e17fd054900a1afb4")
},
{
"_id" : ObjectId("5e1b8fac96516432845e364c"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a127517fd054900a1afb5")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916f"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a127a17fd054900a1afb6")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916e"),
"startsAt" : 64800000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a23f8bf353f493c74e8ae")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916d"),
"startsAt" : 61380000,
"endsAt" : 83154000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a2407bf353f493c74e8af")
}
],
"socialMedias" : [
{
"_id" : ObjectId("5e1d082641c52d4a587a9191"),
"socialMediaId" : ObjectId("5e10089a3330ad05d4e1867d"),
"url" : "rewrwerwerwerwerwerwerwer"
}
],
"paymentTerms" : [
{
"_id" : ObjectId("5e1d143041c52d4a587a91b7"),
"paymentTermId" : ObjectId("5e1a2277bf353f493c74e8a7")
},
{
"_id" : ObjectId("5e1d143041c52d4a587a91b6"),
"paymentTermId" : ObjectId("5e1a228cbf353f493c74e8a8")
},
{
"_id" : ObjectId("5e1d143041c52d4a587a91b5"),
"paymentTermId" : ObjectId("5e1a229ebf353f493c74e8a9")
}
],
"sections" : [
{
"_id" : ObjectId("5e1e535441c52d4a587a9208"),
"name" : "Camisetas",
"products" : [
{
"_id" : ObjectId("5e1e662f044582129844ffd5"),
"name" : "DonJuan M",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 0,
"validFrom" : ISODate("2020-01-15T01:08:49.552Z"),
"validTo" : ISODate("2020-01-15T01:08:49.552Z"),
"enabled" : true
}
]
},
{
"_id" : ObjectId("5e20ec889c05f229a484ea3d"),
"name" : "Imãs",
"products" : [
{
"_id" : ObjectId("5e20ec889c05f229a484ea3e"),
"name" : "Imã",
"description" : "Imã",
"quantityAvailable" : 0,
"image" : "",
"price" : 0,
"validFrom" : ISODate("0001-01-01T00:00:00Z"),
"validTo" : ISODate("9999-12-31T00:00:00Z"),
"enabled" : true
}
]
}
]
}
],
"users" : [
{
"_id" : ObjectId("5e10fc2adc147a373c312144")
},
{
"_id" : ObjectId("5e11ff8003eb832ef84342a6")
}
],
"socialMedias" : [
{
"_id" : ObjectId("5e165672a2204b49c892db74"),
"socialMediaId" : ObjectId("5e10089a3330ad05d4e1867d"),
"url" : "uuuutt"
},
{
"_id" : ObjectId("5e15385fb3a0aa1004ac3598"),
"socialMediaId" : ObjectId("5e1009043330ad05d4e1867f"),
"url" : "jkkjkjkjkjk"
}
],
"sections" : [
{
"_id" : ObjectId("5e15313b2e985e16ec4e7413"),
"name" : "Bebidas",
"products" : [
{
"_id" : ObjectId("5e1e6381044582129844ffc2"),
"name" : "Coca Cola Zero 2 Litros",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 18.39,
"validFrom" : ISODate("1970-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
},
{
"_id" : ObjectId("5e1e6381044582129844ffc3"),
"name" : "Coca Cola 2 Litros",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 21.42,
"validFrom" : ISODate("1970-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
},
{
"_id" : ObjectId("5e1e662f044582129844ffda"),
"name" : "Cerveja Heineken Lata 350ml",
"description" : "Cerveja Heineken Lata 350ml",
"quantityAvailable" : 0,
"image" : "volkswagen-polo.jpg",
"price" : 1.55,
"validFrom" : ISODate("2020-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
}
]
},
{
"_id" : ObjectId("5e20e8de9c05f229a484ea27"),
"name" : "Esfihas",
"products" : [
{
"_id" : ObjectId("5e20e8de9c05f229a484ea28"),
"name" : "Esfiha de carne",
"description" : "Esfiha de carne",
"quantityAvailable" : 0,
"image" : "",
"price" : 5,
"validFrom" : ISODate("2020-01-01T00:00:00Z"),
"validTo" : null,
"enabled" : true
}
]
}
],
"__v" : 0
}
{
"_id" : ObjectId("5e0ffd23991918424c8d7c3b"),
"name" : "Pizza Ruth",
"active" : true,
"users" : [ ],
"socialMedias" : [ ],
"branches" : [ ],
"sections" : [ ],
"__v" : 0
}
{
"_id" : ObjectId("5e0ffd3d991918424c8d7c3c"),
"name" : "Feijão de Corda",
"active" : true,
"users" : [ ],
"socialMedias" : [ ],
"branches" : [ ],
"sections" : [ ],
"__v" : 0
}
The fields validFrom and validTo (Date fields) from the collection products nested in branches.sections need to be converted to the format yyyy-mm-dd. I can do that with this aggregation pipeline:
{ $unwind: { path: "$branches.sections", preserveNullAndEmptyArrays: true } },
{
"$addFields": {
"branches.sections.products": {
$map: {
input: "$branches.sections.products",
as: "product",
in: {
'_id': "$$product._id",
'name': "$$product.name",
'description': "$$product.description",
'quantityAvailable': "$$product.quantityAvailable",
'image': "$$product.image",
'imageUrl': "$$product.imageUrl",
'price': "$$product.price",
'validFrom' : {"$dateToString": { "date": "$$product.validFrom", "format": "%Y-%d-%m" }},
'validTo' : {"$dateToString": { "date": "$$product.validTo", "format": "%Y-%d-%m" }},
'enabled': "$$product.enabled",
}
}
}
}
}
I can successfully convert those date fields, but I need now to "re-unwind" the array products, in order to be just like before the unwind.
Any clue in how to proceed? Or even a different way to format those dates without having to unwind? Tried dozens of ways of $group, but without any success.
You just need to $map over each nested array to drill upload the validTo and validFrom field
.aggregate([
{ "$addFields": {
"branches": {
"$map": {
"input": "$branches",
"as": "branch",
"in": {
"$mergeObjects": [
"$$branch",
{ "section": {
"$map": {
"input": "$$branch.sections",
"as": "section",
"in": {
"$mergeObjects": [
"$$section",
{ "product": {
"$map": {
"input": "$$section.products",
"as": "product",
"in": {
"$mergeObjects": [
"$$product",
{
"validFrom": { "$dateToString": { "date": "$$product.validFrom", "format": "%Y-%d-%m" }},
"validTo": { "$dateToString": { "date": "$$product.validTo", "format": "%Y-%d-%m" }}
}
]
}
}
}}
]
}
}
}}
]
}
}
}
}}
])
MongoPlayground

Problems aggregating MongoDB

I am having problems aggregating my Product Document in MongoDB.
My Product Document is:
{
"_id" : ObjectId("5d81171c2c69f45ef459e0af"),
"type" : "T-Shirt",
"name" : "Panda",
"description" : "Panda's are cool.",
"image" : ObjectId("5d81171c2c69f45ef459e0ad"),
"created_at" : ISODate("2019-09-17T18:25:48.026+01:00"),
"is_featured" : false,
"sizes" : [
"XS",
"S",
"M",
"L",
"XL"
],
"tags" : [ ],
"pricing" : {
"price" : 26,
"sale_price" : 8
},
"categories" : [
ObjectId("5d81171b2c69f45ef459e086"),
ObjectId("5d81171b2c69f45ef459e087")
],
"sku" : "5d81171c2c69f45ef459e0af"
},
And my Category Document is:
{
"_id" : ObjectId("5d81171b2c69f45ef459e087"),
"name" : "Art",
"description" : "These items are our artsy options.",
"created_at" : ISODate("2019-09-17T18:25:47.196+01:00")
},
My aim is to perform aggregation on the Product Document in order to count the number of items within each Category. So I have the Category "Art", I need to count the products are in the "Art" Category:
My current aggregate:
db.product.aggregate(
{ $unwind : "$categories" },
{
$group : {
"_id" : { "name" : "$name" },
"doc" : { $push : { "category" : "$categories" } },
}
},
{ $unwind : "$doc" },
{
$project : {
"_id" : 0,
"name" : "$name",
"category" : "$doc.category"
}
},
{
$group : {
"_id" : "$category",
"name": { "$first": "$name" },
"items_in_cat" : { $sum : 1 }
}
},
{ "$sort" : { "items_in_cat" : -1 } },
)
Which does actually work but not as I need:
{
"_id" : ObjectId("5d81171b2c69f45ef459e082"),
"name" : null, // Why is the name of the category no here?
"items_in_cat" : 4
},
As we can see the name is null. How can I aggregate the output to be:
{
"_id" : ObjectId("5d81171b2c69f45ef459e082"),
"name" : "Art",
"items_in_cat" : 4
},
We need to use $lookup to fetch the name from Category collection.
The following query can get us the expected output:
db.product.aggregate([
{
$unwind:"$categories"
},
{
$group:{
"_id":"$categories",
"items_in_cat":{
$sum:1
}
}
},
{
$lookup:{
"from":"category",
"let":{
"id":"$_id"
},
"pipeline":[
{
$match:{
$expr:{
$eq:["$_id","$$id"]
}
}
},
{
$project:{
"_id":0,
"name":1
}
}
],
"as":"categoryLookup"
}
},
{
$unwind:{
"path":"$categoryLookup",
"preserveNullAndEmptyArrays":true
}
},
{
$project:{
"_id":1,
"name":{
$ifNull:["$categoryLookup.name","NA"]
},
"items_in_cat":1
}
}
]).pretty()
Data set:
Collection: product
{
"_id" : ObjectId("5d81171c2c69f45ef459e0af"),
"type" : "T-Shirt",
"name" : "Panda",
"description" : "Panda's are cool.",
"image" : ObjectId("5d81171c2c69f45ef459e0ad"),
"created_at" : ISODate("2019-09-17T17:25:48.026Z"),
"is_featured" : false,
"sizes" : [
"XS",
"S",
"M",
"L",
"XL"
],
"tags" : [ ],
"pricing" : {
"price" : 26,
"sale_price" : 8
},
"categories" : [
ObjectId("5d81171b2c69f45ef459e086"),
ObjectId("5d81171b2c69f45ef459e087")
],
"sku" : "5d81171c2c69f45ef459e0af"
}
Collection: category
{
"_id" : ObjectId("5d81171b2c69f45ef459e086"),
"name" : "Art",
"description" : "These items are our artsy options.",
"created_at" : ISODate("2019-09-17T17:25:47.196Z")
}
{
"_id" : ObjectId("5d81171b2c69f45ef459e087"),
"name" : "Craft",
"description" : "These items are our artsy options.",
"created_at" : ISODate("2019-09-17T17:25:47.196Z")
}
Output:
{
"_id" : ObjectId("5d81171b2c69f45ef459e087"),
"items_in_cat" : 1,
"name" : "Craft"
}
{
"_id" : ObjectId("5d81171b2c69f45ef459e086"),
"items_in_cat" : 1,
"name" : "Art"
}

Need to calculate individual field count from MongoDB embedded collections

I need to count the fields in embedded as well as parent collection in MongoDB.
My document consist of multiple embedded collections. I have to retrieve the count of fields instead of actual data from DB.
This is my sample collection,
{
"_id" : ObjectId("5c58401e354bba286ce4db67"),
"_class" : "com.model.ProductTemplate",
"templateName" : "tempnew",
"printServiceCategories" : [
{
"_id" : "PSC00001",
"createdOn" : ISODate("2019-02-04T13:35:52.503Z"),
"createdBy" : "PRODUCTADMIN",
"isactive" : true,
"serviceCategoryDisplayName" : "Finishing",
"serviceCategoryMappingName" : "Finishing",
"groupTypes" : [
{
"groupTypeId" : "GT00001",
"groupTypeDisplayName" : "Binding",
"groupTypeMappingName" : "Binding",
"printServices" : [
{
"printServiceId" : "PS00003",
"printServiceMappingName" : "coil_bind_blue",
"printServiceDisplayName" : "Coil Bind Blue",
"printServiceImage" : "",
"isDefault" : false,
"createdBy" : "PRODUCTADMIN"
},
{
"printServiceId" : "PS00004",
"printServiceDisplayName" : "Coil Bind Black",
"isDefault" : true,
"createdBy" : "PRODUCTADMIN"
},
{
"printServiceId" : "PS00005",
"printServiceMappingName" : "comb_bind_black",
"printServiceDisplayName" : "Comb Bind Black",
"printServiceImage" : "",
"isDefault" : false,
"createdBy" : "PRODUCTADMIN"
}
],
"createdBy" : "PRODUCTADMIN"
}
]
},
{
"_id" : "PSC00002",
"createdOn" : ISODate("2019-02-04T13:36:32.794Z"),
"createdBy" : "PRODUCTADMIN",
"isactive" : true,
"serviceCategoryDisplayName" : "Media",
"serviceCategoryMappingName" : "Media",
"groupTypes" : [
{
"groupTypeId" : "GT00002",
"groupTypeDisplayName" : "Paper",
"groupTypeMappingName" : "Paper",
"printServices" : [
{
"printServiceId" : "PS00006",
"printServiceMappingName" : "a3",
"printServiceDisplayName" : "A3",
"printServiceImage" : "",
"isDefault" : false,
"createdBy" : "PRODUCTADMIN"
},
{
"printServiceId" : "PS00007",
"printServiceDisplayName" : "A4",
"isDefault" : true,
"createdBy" : "PRODUCTADMIN"
}
],
"createdBy" : "PRODUCTADMIN"
}
]
}
],
"templateCreatedOn" : ISODate("2019-02-04T13:37:34.025Z"),
"vendorid" : "5c5838aef57da72804d72ee0",
"fileoptionstatus" : "withoutFile",
"isactive" : true,
"createdBy" : "CLIENTADMIN",
"additionalServices" : [],
"file" : {
"_id" : null
}
}
Here is above collection of Product Template, I am having three embedded collections namely printServiceCategories, groupTypes,printServices.
printServiceCategories consist of array of groupTypes whereas groupTypes consist of array of printServices.
While fetching data from database using spring boot application I just need
1.count of `printServices` in `Grouptype`
2.count of `Grouptype` in `printServiceCategories` .
3.Similarly count of `printServiceCategories` in `product template`.
Can any one help me to query as per expected output as describe in above?
Try something like below:
db.database.aggregate([
{
$match: { "_id":ObjectId("5c8a4f4e7c5f002838e61b24") }
},
{
$facet: {
countOfPrintServices: [
{
$unwind: "$printServiceCategories"
},
{
$unwind: "$printServiceCategories.groupTypes"
},
{
$unwind: "$printServiceCategories.groupTypes.printServices"
},
{
$group: {
_id: "$_id",
count:{$sum:1}
}
}
],
countOfGrouptypeInPrintServiceCategories : [
{
$unwind: "$printServiceCategories"
},
{
$unwind: "$printServiceCategories.groupTypes"
},
{
$group: {
_id: "$_id",
count:{$sum:1}
}
}
],
countOfPrintServiceCategoriesInProductTemplate: [
{
$unwind: "$printServiceCategories"
},
{
$group: {
_id: "$_id",
count:{$sum:1}
}
}
]
}
}
])
It might be not the optimized solution by you will get your desired result.
{
"countOfPrintServices" : [
{
"_id" : ObjectId("5c58401e354bba286ce4db67"),
"count" : 5
}
],
"countOfGrouptypeInPrintServiceCategories" : [
{
"_id" : ObjectId("5c58401e354bba286ce4db67"),
"count" : 2
}
],
"countOfPrintServiceCategoriesInProductTemplate" : [
{
"_id" : ObjectId("5c58401e354bba286ce4db67"),
"count" : 2
}
]
}

How to return all project employees?

I have datas of following format collection(projects) inside my database:
{ "_id" : ObjectId("5981a80f223e491a58230e5d"), "id" : 2, "name" : "gbqplhlqxzwl", "managerId" : 65151, "startDate" : "03.11.1999", "finishDate" : "02.01.2003", "projectStatus" : "POSTPONED", "participants" : [ ], "estimatedBudget" : 6017891.811079914 }
{ "_id" : ObjectId("5981a80f223e491a58230e5e"), "id" : 3, "name" : "erfekfsdgryu", "managerId" : 83749, "startDate" : "07.07.2007", "finishDate" : "26.12.2027", "projectStatus" : "POSTPONED", "participants" : [ 19229, 81856, 79270, 5509, 70344, 39424 ], "estimatedBudget" : 3086213.8981674756 }
{ "_id" : ObjectId("5981a80f223e491a58230e5f"), "id" : 1, "name" : "jvbzobhppntd", "managerId" : 18925, "startDate" : "29.04.1999", "finishDate" : "13.10.2008", "projectStatus" : "OPEN", "participants" : [ 46100, 96968, 6676, 56121, 4716, 68901, 43990, 48587, 62547, 30292, 65153, 17551, 27083, 20261, 27097, 50036, 86585, 69890, 18790, 22592, 60774, 93709, 78471, 27157, 4328, 36501, 47296, 16831 ], "estimatedBudget" : 3581496.7068344904 }
{ "_id" : ObjectId("5981a80f223e491a58230e60"), "id" : 4, "name" : "cdspkkqwvwld", "managerId" : 62042, "startDate" : "13.03.1998", "finishDate" : "20.06.2007", "projectStatus" : "OPEN", "participants" : [ 53480, 60897, 23677, 22064, 60807, 66637, 84609, 28378, 87143, 27675, 79283, 94992, 20429, 48769, 91671, 41747, 21651, 91134, 41684, 57228, 51949, 18756, 45679, 87781, 67287, 6902, 27526 ], "estimatedBudget" : 2126283.953787842 }
....
I need to find the busiest employee and list all his projects.
participants array contains employee ids who participate in the project.
I use the following query to find the busiest employee:
db.projects.aggregate(
{
$unwind: '$participants'
},
{
$addFields: {
count: 1
}
},
{
$group: {
_id : '$participants',
participation_count : {
'$sum':'$count'
}
}
},
{
$sort:{participation_count:-1}
},
{
$limit:1
}
)
and this work correctly. But I have no ideas how to list all his projects.
any ideas?
db.projects.aggregate(
[
{
$unwind: '$participants'
},
{
$addFields: {
count: 1
}
},
{
$group: {
_id : '$participants',
participation_count : {'$sum':'$count'},
projectId : {$push: '$id'}
}
},
{
$sort:{participation_count:-1}
},
{
$limit:1
}
],
{
allowDiskUse:true
}
)