How to filter a nested/lower subdocument - mongodb

Say if I have a result like this:
{
"_id" : ObjectId("5b722d06c23b5f2bd0329a41"),
"name" : "test",
"item" : {
"_id" : ObjectId("5b722d07c23b5f2bd0329a53"),
"display_name" : "",
"image" : "http://via.placeholder.com/700x500/ffffff/000000/?text=No%20Image&",
"is_private" : true,
"details" : [
{
"is_private" : false,
"type" : "text",
"_id" : ObjectId("5b722d06c23b5f2bd0329a44"),
"title" : "Name",
"content" : "",
"order" : 0
},
{
"is_private" : false,
"type" : "text",
"_id" : ObjectId("5b722d06c23b5f2bd0329a43"),
"title" : "Price",
"content" : "",
"order" : 1
},
{
"is_private" : false,
"type" : "text",
"_id" : ObjectId("5b722d06c23b5f2bd0329a42"),
"title" : "Company",
"content" : "",
"order" : 2
}
],
"tags" : [ ],
"__v" : 0
}
}
and I want to filter by item.details.is_private, how should I do this? I want to return all properties of item but filter out any item.details.is_private if it is true
I am currently projecting it as:
{
"$project": {
name: 1,
item: 1
}
}
but am not sure how to implement $filter in this setting

You can try using $addsFields with $filter aggregation
db.collection.aggregate([
{ "$addFields": {
"item.details": {
"$filter": {
"input": "$item.details",
"as": "detail",
"cond": {
"$eq": [ "$$detail.is_private", true ]
}
}
}
}}
])

Related

How to sort by mutiple fields with conditons in MongoDB

Need help to sort these documents:
const docs = Docs.find(
{
'publishedOn.profileId': groupProfile._id,
},
{ sort: { ??? }}
);
I need to find documents which has defined 'publishedOn.profileId' and
sort by 'awards.type' = 'challengeWinner' and by its 'awards.score'
Not all document has awards.type = 'challengeWinner'. I need to
take on the top 'awards.score' = 1, then 2, then 3 and then the rest by 'writtenDate'.
I have no idea how to fix it. Is it possible?
[
{
"_id" : "5FW9EDW8gi3M8R7XK",
"createdAt" : ISODate("2021-06-13T00:11:48.638Z"),
"title" : "My solution",
"writtenDateType" : 4,
"writtenDate" : ISODate("2021-06-13T00:00:00.000Z"),
"userId" : "dC35hwe6XMRhvqWBv",
"publishedOn" : [
{
"profileId" : "36oPw2zxYCpKxfiu2",
"publishedDate" : ISODate("2021-06-13T00:11:48.787Z"),
"userId" : "dC35hwe6XMRhvqWBv"
},
{
"profileId" : "9y2RwJpzzyk29ApiC",
"userId" : "dC35hwe6XMRhvqWBv",
"publishedDate" : ISODate("2021-06-13T00:16:01.529Z")
}
],
"awards" : [
{
"type" : "topPoem",
"score" : 5,
"addedAt" : ISODate("2021-06-24T23:04:10.454Z"),
"updatedAt" : ISODate("2021-06-25T23:30:00.069Z")
},
{
"type" : "challengeWinner",
"score" : 2,
"challengeId" : "9y2RwJpzzyk29ApiC",
"addedAt" : ISODate("2021-06-24T23:04:10.454Z"),
"updatedAt" : ISODate("2021-06-25T23:30:00.069Z")
}
]
},
{
"_id" : "upzvo8BeHyQ9r9Yfv",
"createdAt" : ISODate("2021-06-19T15:35:13.716Z"),
"title" : "Briches",
"writtenDateType" : 2,
"writtenDate" : ISODate("2003-01-01T00:00:00.000Z"),
"userId" : "A32228XMuZqxFe4Kz",
"publishedOn" : [
{
"profileId" : "MLGkCtNyZ64bGKedG",
"publishedDate" : ISODate("2021-06-19T15:35:13.861Z"),
"userId" : "A32228XMuZqxFe4Kz"
},
{
"profileId" : "9y2RwJpzzyk29ApiC",
"userId" : "A32228XMuZqxFe4Kz",
"publishedDate" : ISODate("2021-06-19T15:35:36.280Z")
}
],
"awards" : [
{
"type" : "challengeWinner",
"score" : 1,
"challengeId" : "9y2RwJpzzyk29ApiC",
"addedAt" : ISODate("2021-06-24T22:59:00.948Z"),
"updatedAt" : ISODate("2021-06-25T23:30:00.067Z"),
"claps" : 19,
"clapsUsers" : 4
},
{
"type" : "suggestedHomepage",
"score" : 1,
"addedAt" : ISODate("2021-06-24T22:59:59.981Z"),
"updatedAt" : ISODate("2021-06-24T22:59:59.981Z")
}
]
}
]
I just learned and tried to solve your problem. I used aggregate to do the filter in your data.
First I selected all the items which $match the `publishedOn.profileId".
Then, I $project(ed) the items that are needed. In this case, I took the writtenDate and the matching awards.
In order to choose the needed value from awards, I $filter (ed) the award type.
Last, I did $sort for the award score first and then writtenDate,
db.collection.aggregate([
{
"$match": {
"publishedOn.profileId": "9y2RwJpzzyk29ApiC"
}
},
{
"$project": {
"writtenDate": 1,
"awards": {
"$filter": {
"input": "$awards",
"as": "award",
"cond": {
"$eq": [
"$$award.type",
"challengeWinner"
]
}
}
}
}
},
{
"$sort": {
"awards.score": 1,
"writtenDate": 1,
}
}
])
Working of above query: https://mongoplayground.net/p/MzWQCR2Gshg
Happy Coding !!!

$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"
}

Return specific array value field in aggregate

I have a issue in MongoDB i'm trying to build a very complex aggregate query, and its work almost as i want it, but i still have trobles, and the problems is i need to move a spefiect field so i can use it later.
My aggregate look like this right now.
db.getCollection('travel_sights').aggregate([{
'$match': {
'preview.photo' : {
'$exists':true
},
'_id': {
'$in' : [ObjectId("5b7af9701fbad410e10f32f7")]
}
}
},{
'$unwind' : '$preview.photo'
}, {
'$lookup':{
'from' : 'media_data',
'localField' : '_id',
'foreignField':'bind',
'as':'media'
}
}])
and it will return data like this.
{
"_id" : ObjectId("5b7af9701fbad410e10f32f7"),
"preview" : {
"photo" : {
"id" : ObjectId("5b7affea1fbad441494a663b"),
"sort" : 0
}
},
"media" : [
{
"_id" : ObjectId("5b7affea1fbad441494a663b")
},
{
"_id" : ObjectId("5b7b002d1fbad441494a663c")
},
{
"_id" : ObjectId("5b7b00351fbad441494a663d")
},
{
"_id" : ObjectId("5b7d9baa1fbad410de638bbb")
},
{
"_id" : ObjectId("5b7d9bae1fbad410e10f32f9")
},
{
"_id" : ObjectId("5b7d9bb11fbad441494a663e")
},
{
"_id" : ObjectId("5b7d9bb41fbad4ff97273402")
},
{
"_id" : ObjectId("5b7d9bb71fbad4ff99527e82")
},
{
"_id" : ObjectId("5b7d9bbb1fbad410de638bbc")
},
{
"_id" : ObjectId("5b7d9bbe1fbad410e10f32fa")
},
{
"_id" : ObjectId("5b7d9bc11fbad441494a663f")
},
{
"_id" : ObjectId("5b7d9bc41fbad4ff97273403")
},
{
"_id" : ObjectId("5b7d9bc71fbad4ff99527e83")
},
{
"_id" : ObjectId("5b7d9bca1fbad410de638bbd")
},
{
"_id" : ObjectId("5b7d9bcd1fbad441494a6640")
},
{
"_id" : ObjectId("5b7d9bd01fbad4ff97273404")
}
]
}
{
"_id" : ObjectId("5b7af9701fbad410e10f32f7"),
"preview" : {
"photo" : {
"id" : ObjectId("5b7b002d1fbad441494a663c"),
"sort" : 0
}
},
"media" : [
{
"_id" : ObjectId("5b7affea1fbad441494a663b")
},
{
"_id" : ObjectId("5b7b002d1fbad441494a663c")
},
{
"_id" : ObjectId("5b7b00351fbad441494a663d")
},
{
"_id" : ObjectId("5b7d9baa1fbad410de638bbb")
},
{
"_id" : ObjectId("5b7d9bae1fbad410e10f32f9")
},
{
"_id" : ObjectId("5b7d9bb11fbad441494a663e")
},
{
"_id" : ObjectId("5b7d9bb41fbad4ff97273402")
},
{
"_id" : ObjectId("5b7d9bb71fbad4ff99527e82")
},
{
"_id" : ObjectId("5b7d9bbb1fbad410de638bbc")
},
{
"_id" : ObjectId("5b7d9bbe1fbad410e10f32fa")
},
{
"_id" : ObjectId("5b7d9bc11fbad441494a663f")
},
{
"_id" : ObjectId("5b7d9bc41fbad4ff97273403")
},
{
"_id" : ObjectId("5b7d9bc71fbad4ff99527e83")
},
{
"_id" : ObjectId("5b7d9bca1fbad410de638bbd")
},
{
"_id" : ObjectId("5b7d9bcd1fbad441494a6640")
},
{
"_id" : ObjectId("5b7d9bd01fbad4ff97273404")
}
]
}
{
"_id" : ObjectId("5b7af9701fbad410e10f32f7"),
"preview" : {
"photo" : {
"id" : ObjectId("5b7b00351fbad441494a663d"),
"sort" : 0,
"primary" : false
}
},
"media" : [
{
"_id" : ObjectId("5b7affea1fbad441494a663b")
},
{
"_id" : ObjectId("5b7b002d1fbad441494a663c")
},
{
"_id" : ObjectId("5b7b00351fbad441494a663d")
},
{
"_id" : ObjectId("5b7d9baa1fbad410de638bbb")
},
{
"_id" : ObjectId("5b7d9bae1fbad410e10f32f9")
},
{
"_id" : ObjectId("5b7d9bb11fbad441494a663e")
},
{
"_id" : ObjectId("5b7d9bb41fbad4ff97273402")
},
{
"_id" : ObjectId("5b7d9bb71fbad4ff99527e82")
},
{
"_id" : ObjectId("5b7d9bbb1fbad410de638bbc")
},
{
"_id" : ObjectId("5b7d9bbe1fbad410e10f32fa")
},
{
"_id" : ObjectId("5b7d9bc11fbad441494a663f")
},
{
"_id" : ObjectId("5b7d9bc41fbad4ff97273403")
},
{
"_id" : ObjectId("5b7d9bc71fbad4ff99527e83")
},
{
"_id" : ObjectId("5b7d9bca1fbad410de638bbd")
},
{
"_id" : ObjectId("5b7d9bcd1fbad441494a6640")
},
{
"_id" : ObjectId("5b7d9bd01fbad4ff97273404")
}
]
}
and what you can se the last data have preview.photo.primary on it, and this field i want to return when i'm done with my aggregate query.
My final query look like this:
db.getCollection('travel_sights').aggregate([{
'$match': {
'preview.photo' : {
'$exists':true
},
'_id': {
'$in' : [ObjectId("5b7af9701fbad410e10f32f7")]
}
}
},{
'$unwind' : '$preview.photo'
}, {
'$lookup':{
'from' : 'media_data',
'localField' : '_id',
'foreignField':'bind',
'as':'media'
}
},{
'$unwind':'$media'
},{
'$project' : {
'preview' : 1,
'media': 1,
}
}, {
'$group': {
'_id':'$media._id',
'primary': {
'$first':'$preview'
}
}
}])
The problem here is when i want $preview return so i can find the primary about it, its allways only return the first where the value not exists, if i use $push the problem is i get every thing.
is there a way so i can pick the right primary value in my return? have trying $addFields to but whitout eny kind of lock.
Travel_sights data:
{
"_id" : ObjectId("5b7af9701fbad410e10f32f7"),
"city_id" : ObjectId("5b6d0cb6222d4c70b803eaeb"),
"activated" : true,
"deleted" : false,
"url" : "url is here",
"name" : "title of it here",
"updated_at" : ISODate("2018-08-22T17:22:27.000Z"),
"content" : "content here",
"preview" : {
"photo" : [
{
"id" : ObjectId("5b7affea1fbad441494a663b"),
"sort" : 0
},
{
"id" : ObjectId("5b7b002d1fbad441494a663c"),
"sort" : 0
},
{
"id" : ObjectId("5b7b00351fbad441494a663d"),
"sort" : 0,
"primary" : true
},
{
"id" : ObjectId("5b7d9baa1fbad410de638bbb"),
"sort" : 0
},
{
"id" : ObjectId("5b7d9bae1fbad410e10f32f9"),
"sort" : 0
},
{
"id" : ObjectId("5b7d9bb11fbad441494a663e"),
"sort" : 0
},
{
"id" : ObjectId("5b7d9bb41fbad4ff97273402"),
"sort" : 0,
"primary" : false
},
{
"id" : ObjectId("5b7d9bb71fbad4ff99527e82"),
"sort" : 0,
"primary" : false
},
{
"id" : ObjectId("5b7d9bbb1fbad410de638bbc"),
"sort" : 0
},
{
"id" : ObjectId("5b7d9bbe1fbad410e10f32fa"),
"sort" : 0
},
{
"id" : ObjectId("5b7d9bc11fbad441494a663f"),
"sort" : 0
},
{
"id" : ObjectId("5b7d9bc41fbad4ff97273403"),
"sort" : 0,
"primary" : false
},
{
"id" : ObjectId("5b7d9bc71fbad4ff99527e83"),
"sort" : 0,
"primary" : false
},
{
"id" : ObjectId("5b7d9bca1fbad410de638bbd"),
"sort" : 0,
"primary" : false
},
{
"id" : ObjectId("5b7d9bcd1fbad441494a6640"),
"sort" : 0,
"primary" : false
},
{
"id" : ObjectId("5b7d9bd01fbad4ff97273404"),
"sort" : 0
}
]
}
}
3 sample foto bind data here:
{
"_id" : ObjectId("5b7affea1fbad441494a663b"),
"file-name" : "55575110311__0F115282-B5A0-4654-AA44-B7DC2C682992.jpeg",
"options" : [
ObjectId("5b6fb855222d4c70b8041093")
],
"type" : "images",
"files" : [
{
"width" : 70,
"height" : 53
},
{
"width" : 400,
"height" : 300
},
{
"width" : 800,
"height" : 600
},
{
"width" : 1600,
"height" : 1200
}
],
"bind" : [
ObjectId("5b7af9701fbad410e10f32f7")
]
}
{
"_id" : ObjectId("5b7b002d1fbad441494a663c"),
"file-name" : "55575110748__E7B07EFD-9F7E-40D6-8B57-38F708E4C0C0.jpeg",
"options" : [
ObjectId("5b6fb855222d4c70b8041093")
],
"type" : "images",
"files" : [
{
"width" : 70,
"height" : 53
},
{
"width" : 400,
"height" : 300
},
{
"width" : 800,
"height" : 600
},
{
"width" : 1600,
"height" : 1200
}
],
"bind" : [
ObjectId("5b7af9701fbad410e10f32f7")
],
"description" : "this is secoudn demo!",
"title" : "demo 3"
}
{
"_id" : ObjectId("5b7b00351fbad441494a663d"),
"file-name" : "paris2.jpg",
"options" : [
ObjectId("5b6fb855222d4c70b8041093")
],
"type" : "images",
"files" : [
{
"width" : 70,
"height" : 53
},
{
"width" : 400,
"height" : 300
},
{
"width" : 800,
"height" : 600
},
{
"width" : 1600,
"height" : 1200
}
],
"bind" : [
ObjectId("5b7af9701fbad410e10f32f7")
],
"description" : "this is a demo1 :)",
"title" : "demo"
}
You can filter out the element from the array where the primary field exists using $filter aggregation and then easily $group with the media._id field and get the $first document value.
Finally your query will be
db.getCollection("travel_sights").aggregate([
{ "$match": {
"preview.photo" : { "$exists":true },
"_id": { "$in" : [ ObjectId("5b7af9701fbad410e10f32f7") ] }
}},
{ "$addFields": {
"preview.photo": {
"$arrayElemAt": [
{ "$filter": {
"input": "$preview.photo",
"as": "photo",
"cond": { "$ne": [ "$$photo.primary", undefined ] }
}}, 0
]
}
}},
{ "$lookup":{
"from" : "media_data",
"localField" : "_id",
"foreignField": "bind",
"as": "media"
}},
{ "$unwind":"$media" },
{ "$project" : { "preview" : 1, "media": 1, }},
{ "$group": {
"_id": "$media._id",
"primary": { "$first": "$preview" }
}}
])

Group by specific element of array with mongo aggregation framework

Is it possible to use the aggregation framework to group by a specific element of an array?
Such that with documents like this:
{
name: 'Russell',
favourite_foods: [
{ name: 'Pizza', type: 'Four Cheeses' },
{ name: 'Burger', type: 'Veggie'}
],
height: 6
}
I could get a distinct list of top favourite foods (ie. foods at index 0) along with the height of the tallest person who's top favourite food that is?
Something like this (although it doesn't work as the array index access dot notation doesn't seem to work in the aggregation framework):
db.people.aggregate([
{ $group : { _id: "$favourite_foods.0.name", max_height: { $max : "$height" } } }
])
Seems like you are relying on the favorite food for each person being first in the array. If so, there is an aggregation framework operator you can take advantage of.
Here is the pipeline you can use:
db.people.aggregate(
[
{
"$unwind" : "$favourite_foods"
},
{
"$group" : {
"_id" : {
"name" : "$name",
"height" : "$height"
},
"faveFood" : {
"$first" : "$favourite_foods"
}
}
},
{
"$group" : {
"_id" : "$faveFood.name",
"height" : {
"$max" : "$_id.height"
}
}
}
])
On this sample dataset:
> db.people.find().pretty()
{
"_id" : ObjectId("508894efd4197aa2b9490741"),
"name" : "Russell",
"favourite_foods" : [
{
"name" : "Pizza",
"type" : "Four Cheeses"
},
{
"name" : "Burger",
"type" : "Veggie"
}
],
"height" : 6
}
{
"_id" : ObjectId("5088950bd4197aa2b9490742"),
"name" : "Lucy",
"favourite_foods" : [
{
"name" : "Pasta",
"type" : "Four Cheeses"
},
{
"name" : "Burger",
"type" : "Veggie"
}
],
"height" : 5.5
}
{
"_id" : ObjectId("5088951dd4197aa2b9490743"),
"name" : "Landy",
"favourite_foods" : [
{
"name" : "Pizza",
"type" : "Four Cheeses"
},
{
"name" : "Pizza",
"type" : "Veggie"
}
],
"height" : 5
}
{
"_id" : ObjectId("50889541d4197aa2b9490744"),
"name" : "Augie",
"favourite_foods" : [
{
"name" : "Sushi",
"type" : "Four Cheeses"
},
{
"name" : "Pizza",
"type" : "Veggie"
}
],
"height" : 6.2
}
You get these results:
{
"result" : [
{
"_id" : "Pasta",
"height" : 5.5
},
{
"_id" : "Pizza",
"height" : 6
},
{
"_id" : "Sushi",
"height" : 6.2
}
],
"ok" : 1
}
Looks like it isn't currently possible to extract a specific element from an array in aggregation:
https://jira.mongodb.org/browse/SERVER-4589
JUST add more information about the result after using "$wind":
DOCUMENT :
> db.people.find().pretty()
{
"_id" : ObjectId("508894efd4197aa2b9490741"),
"name" : "Russell",
"favourite_foods" : [
{
"name" : "Pizza",
"type" : "Four Cheeses"
},
{
"name" : "Burger",
"type" : "Veggie"
}
],
"height" : 6
},
...
AGGREAGATION :
db.people.aggregate([{
$unwind: "$favourite_foods"
}]);
RESULT :
{
"_id" : ObjectId("508894efd4197aa2b9490741"),
"name" : "Russell",
"favourite_foods" :{
"name" : "Pizza",
"type" : "Four Cheeses"
},
"height" : 6
},
{
"_id" : ObjectId("508894efd4197aa2b9490741"),
"name" : "Russell",
"favourite_foods" : {
"name" : "Burger",
"type" : "Veggie"
},
"height" : 6
}
In Addition:
If there are more than two array fields in one collection record,
we can use "$project" stage to specify the array field.
db.people.aggregate([
{
$project:{
"favourite_foods": 1
}
},
{
$unwind: "$favourite_foods"
}
]);
I think you can make use of the $project and $unwind operators (let me know if this isn't what you're trying to accomplish):
> db.people.aggregate(
{$unwind: "$favourite_foods"},
{$project: {food : "$favourite_foods", height: 1}},
{$group : { _id: "$food", max_height: { $max : "$height" } } })
{
"result" : [
{
"_id" : {
"name" : "Burger",
"type" : "Veggie"
},
"max_height" : 6
},
{
"_id" : {
"name" : "Pizza",
"type" : "Four Cheeses"
},
"max_height" : 6
}
],
"ok" : 1
}
http://docs.mongodb.org/manual/applications/aggregation/
Since mongoDB version 3.2 You can simply use $arrayElemAt and $max:
db.collection.aggregate([
{
$set: {favourite_foods: {$arrayElemAt: ["$favourite_foods", 0]}}
},
{
$group: {
_id: "$favourite_foods.name",
maxHeight: {$max: "$height"}
}
}
])
Playground example