quering a data with multiple collections in mongodb - mongodb

I have a question on multiple collections in mongoDB.
I have 3 collections in my database and the collections names are Building, History and basic_amenities.
My question is, i want to retrieve the data of building ,history and basi_amenties to a particular building . I mean i want the data from building ,history and basic_amenities.
I want to do using aggregate concept. Is it possible to do like that or else is there any alternative method.
Building:
{
"_id" : "B1",
"Sale_type" : "Rental",
"Building_name" : "swamy",
"Available_apartments" : {
"Apartment_num" : "A6",
"Apartment_num" : "A9"
},
"Owner" : [
"sreekanth Buddha",
"sreekanthb6#gmail.com"
],
"Address" : {
"Street" : "blumenstrasse",
"Plot_no" : "13",
"City" : "Hamburg",
"State" : "lower saxony",
"Country" : "Germany",
"Postal_code" : "68245"
},
"Rental" : {
"Currency" : "EUR",
"Rental_price" : "10000",
"Available_date" : "02.03.2015",
"Deposit_amount" : "60000 EUR"
},
"Total_area" : "1200 sq meters",
"Apartment_id" : [
{
"id1" : "A1"
},
{
"id2" : "A5"
},
{
"id3" : "A7"
},
{
"id4" : "A2"
},
{
"id5" : "A9"
}
],
"Features" : {
"No_of_apartments" : "70",
"Community_hall" : "1",
"Garden" : 3,
"Office_room" : 1,
"Parking" : "yes",
"Play_ground" : "yes"
}
}
History:
"_id" : "H-B1",
"Property_id" : "B1",
"Builtyear" : "April 1995",
"year_of_registration" : [
{
"year" : ISODate("1995-04-15T23:00:00.000Z"),
"name" : "krishna malli"
},
{
"year" : ISODate("2008-07-16T23:00:00.000Z"),
"name" : "manoj kumar alluri"
},
{
"year" : ISODate("2014-10-29T23:00:00.000Z"),
"name" : "Ram dev swamy"
}
],
"Renovate" : [
{
"1995" : " building painting Renovated"
},
{
"2008" : " pipeline system was renovated"
},
{
"2014" : " roof was renovated"
}
]
}
**Basic_amenities:**
{
"_id" : "BA-B1",
"Property_id" : "B1",
"hospital " : "5 km",
"bahn_station" : "6 km ",
"restaurant" : "4 km",
"University" : "20 km",
"police_station" : "8 km",
"Airport" : "40 km",
"city_center" : " 5 km",
"Public_transp_type" : [
{
"Bus" : "35"
},
{
"tram" : "5"
},
{
"train_station" : "5km"
}
],
"keylandmark" : "Altstadt",
"future_activity" : "church constructing"
}
Can anyone help me how to query this data using aggregations concept or else is there any alternative method? please help me
Regards
Sreekanth

Related

Find a nested object field inside an array in mongodb aggregate

I have this object as below.
{
"_id" : ObjectId("5ec80a981e89a84b19934039"),
"status" : "active",
"organizationId" : "1",
"productId" : "1947",
"name" : "BOOKEND & PAPER WEIGHT SET – ZODIAC PIG – RED COPPER + PLATINUM",
"description" : "This global exclusive Zodiac bookend and paperweight set from Zuny will stand auspiciously on your bookcase and table, spreading good luck and fortune throughout your home just in time for the Year of the Pig.",
"brand" : "ZUNY",
"created" : "2018-09-28 00:00:00",
"updated" : "2020-05-22 09:19:07",
"mainImage" : "https://",
"availableOnline" : true,
"colors" : [
{
"images" : [
{
"type" : "studio",
"url" : "https://"
},
{
"type" : "studio",
"url" : "https://"
},
{
"type" : "studio",
"url" : "https://"
}
],
"extraInfo" : [
{
"type" : "text-tag",
"title" : "CATEGORY",
"tags" : [
"HOME FURNISHING & DÉCOR",
"LIFESTYLE"
]
},
{
"type" : "text-tag",
"title" : "BRAND",
"tags" : [
"ZUNY"
]
},
{
"type" : "text-tag",
"title" : "COLOUR",
"tags" : [
"GOLD",
"ROSE GOLD"
]
},
{
"type" : "text-tag",
"title" : "SEASON",
"tags" : [
"AW(2018)"
]
},
{
"type" : "text-tag",
"title" : "HASHTAG",
"tags" : [
"BOOKCASES",
"BOOKEND",
"COLOUR",
"EXCLUSIVE",
"GLOBAL EXCLUSIVE",
"HOME",
"LEATHER",
"MOTIF",
"OBJECTS",
"PAPER",
"PAPERWEIGHT",
"PLATINUM",
"SET",
"SYNTHETIC",
"ZODIAC",
"HANDMADE",
"time"
]
}
],
"_id" : ObjectId("5ec80a981e89a84b1993403a"),
"colorId" : "1",
"color" : "ROSE GOLD",
"status" : "active",
"sizes" : [
{
"extraInfo" : [
{
"type" : "text-block",
"title" : "Size And Fit",
"text" : ""
},
{
"type" : "text-block",
"title" : "Information",
"text" : "Global exclusive. Colour: Copper/Platinum. Set includes: Zodiac Pig bookend (x 1), Zodiac Pig paperweight (x 1). Metallic copper- and platinum-tone synthetic leather. Pig motif. Iron pellet filling. Handmade"
}
],
"_id" : ObjectId("5ec80a981e89a84b1993403b"),
"sizeId" : "1",
"neo" : "0210111790664",
"size" : "*",
"originalPrice" : "1060.00",
"sellingPrice" : "1060.00",
"discountPercent" : "0.00",
"url" : "https://",
"status" : "active",
"currency" : "HK$",
"stores" : [
{
"storeId" : "1",
"quantity" : 70,
"_id" : ObjectId("5ec80a981e89a84b1993403c"),
"available" : 70,
"reserved" : 0,
"name" : "Park Street",
"status" : "active"
},
{
"storeId" : "2",
"quantity" : 95,
"_id" : ObjectId("5ec80a981e89a84b1993403d"),
"name" : "Rashbehari",
"status" : "active"
}
]
}
]
}
],
"__v" : 0
}
I want the output as follows
{
"name": "Mock Collection",
"collectionId": "92",
"products": [
{
"title": "GLOBAL EXCLUSIVE OFF-SHOULDER SHIRT DRESS",
"imageUrl": "https://",
"productId": "21174",
"currency": "" // This should be this.colors[0].sizes[0].currency
},
]
}
How to get the nested field. I tried using arrayElemAt by which I was able to get to colors[0]. But I am confused how to get inside the nested object of sizes from there. Also the currency node should have the exact value. It comes like currency:{currency: value} which I don't want.
Please help!
Not sure how you've got that output but to extract currency from first object of sizes then you need to try this :
db.collection.aggregate([
{
$project: {
currency: {
$arrayElemAt: [
{
$arrayElemAt: [ "$colors.sizes.currency", 0 ] // gives an array of currency values, in your case since you've only one object just an array of one value
},
0
]
}
}
}
])
Test : mongoplayground

Use match to filter result in lookup? MongoDB

I quite can't get how should I use the pipeline to filter the resulting array of my look up here's the code
{
"_id" : ObjectId("5d73d591b35c943a201837e2"),
"itemName" : "Vape",
"itemSellingPrice" : "350",
"itemPurchasePrice" : "300",
"itemAveragePurchasePrice" : "133.33333333333334",
"itemBaseUnit" : "Unit 2",
"itemReorderPoint" : "100",
"itemTotalQuantity" : "300",
"itemSumQuantity" : "500",
"itemLocation" : "1",
"itemSubLocation" : "sub loc 1",
"itemDateCreated" : ISODate("2019-09-07T16:06:41.521Z"),
"itemID" : 88,
"__v" : 0,
"salesData" : [
{
"_id" : ObjectId("5d73e23ed8422d2ba42049b4"),
"salesOrderCustomerName" : "Manong Puring",
"salesOrderInvoiceNumber" : "1123",
"salesOrderAddress" : "Jan lang",
"salesOrderPaymentStatus" : "Open",
"salesOrderTotalPaid" : "0",
"salesOrderTotalAmount" : "2800",
"salesOrderDiscrepancyAmount" : "2800",
"salesOrderItemList" : [
{
"_id" : ObjectId("5d73e23ed8422d2ba42049b5"),
"salesOrderSelectedItem" : "Vape",
"salesOrderAverage" : "133.33333333333334",
"salesOrderNewPrice" : "350",
"salesOrderPurchasePrice" : "300",
"salesOrderQuantity" : "8",
"salesOrderSubTotal" : "2800"
}
],
"salesOrderDateCreated" : ISODate("2019-09-07T16:00:00.000Z"),
"salesOrderSubLocation" : "sub loc 1",
"salesOrderLocation" : "1",
"salesOrderID" : 62,
"__v" : 0
},
{
"_id" : ObjectId("5d73e37164ade31b40775038"),
"salesOrderCustomerName" : "Manong Puring",
"salesOrderInvoiceNumber" : "123",
"salesOrderAddress" : "Jan lang",
"salesOrderPaymentStatus" : "Open",
"salesOrderTotalPaid" : "0",
"salesOrderTotalAmount" : "350",
"salesOrderDiscrepancyAmount" : "350",
"salesOrderItemList" : [
{
"_id" : ObjectId("5d73e37164ade31b40775039"),
"salesOrderSelectedItem" : "Vape",
"salesOrderAverage" : "133.33333333333334",
"salesOrderNewPrice" : "350",
"salesOrderPurchasePrice" : "300",
"salesOrderQuantity" : "1",
"salesOrderSubTotal" : "350"
}
],
"salesOrderDateCreated" : ISODate("2019-09-07T16:00:00.000Z"),
"salesOrderSubLocation" : "sub loc 2",
"salesOrderLocation" : "1",
"salesOrderID" : 63,
"__v" : 0
}
]
}
I only want to get salesData with salesOrderSubLocation: "sub loc 1"
but it is showing data with sub loc 2 also. Searched for a while but can't find an exact problem with mine.
here's my query
db.getCollection('itemmodels').aggregate(
{ '$match': { itemName: 'Vape' } },
{ '$lookup':
{
from: 'itemmodels',
let: { "itemName": "$itemName" },
pipeline: [
{ $match: {
"salesOrderSubLocation": "sub loc 1",
"salesOrderItemList.salesOrderSelectedItem": "$$itemName"
}
}
],
as: 'salesData'
}
})
any idea guys? I don't want to filter the result in the front end because it my cause some problems with tons of data in the future.

How to rewrite nested object in model while update

I have a problem with update object nested in array ("companyBases"), because update scripts overwrites my nested object, i have the following model:
{
"_id" : ObjectId("5d6504541be1e64145c20c66"),
"margin" : 10,
"defaultDeprication" : 10,
"companyBases" : [
{
"_id" : ObjectId("5d6504541be1e64145c20c64"),
"name" : "Tech Parking 2",
"street" : "Traktat Ojca",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.036017,
"lat" : 20.086752
},
"__v" : 0
},
{
"_id" : ObjectId("5d6504541be1e64145c20c65"),
"name" : "Tech Parking 3",
"street" : "ul.Bieżanowska 258B",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.01744,
"lat" : 20.033522
},
"__v" : 0
}
],
}
I'am executing update query:
db.companies.updateOne(
{
_id: ObjectId("5d6504541be1e64145c20c66"),
"companyBases._id": ObjectId("5d6504541be1e64145c20c64")
},
{
$set: {
"companyBases.$": {
"street" : "ul.Małapolska 123"
}
}
}
)
But it overwrites my nested object and now it looking like this:
{
"_id" : ObjectId("5d6504541be1e64145c20c66"),
"margin" : 10,
"defaultDeprication" : 10,
"companyBases" : [
{
"street" : "ul.Małapolska 123"
},
{
"_id" : ObjectId("5d6504541be1e64145c20c65"),
"name" : "Tech Parking 3",
"street" : "ul.Bieżanowska 258B",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.01744,
"lat" : 20.033522
},
"__v" : 0
}
],
}
I would like to rewrite all field from nested object and update fields that i choose in update query.
It should looks like this (without overwriting whole object):
{
"_id" : ObjectId("5d6504541be1e64145c20c66"),
"margin" : 10,
"defaultDeprication" : 10,
"companyBases" : [
{
"_id" : ObjectId("5d6504541be1e64145c20c64"),
"name" : "Tech Parking 2",
"street" : "ul.Małapolska 123",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.036017,
"lat" : 20.086752
},
"__v" : 0
},
{
"_id" : ObjectId("5d6504541be1e64145c20c65"),
"name" : "Tech Parking 3",
"street" : "ul.Bieżanowska 258B",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.01744,
"lat" : 20.033522
},
"__v" : 0
}
],
}
You should use arrayFilter in the update operation, as described here:
positinal filter for arrays
db.companies.updateOne(
{
_id: ObjectId("5d6504541be1e64145c20c66"),
},
{
$set: {
"companyBases.$[element].street: "ul.Małapolska 123"
}
},
{
arrayFilters: [ {"element._id": ObjectId("5d6504541be1e64145c20c64")} ]
}
)

Aggregation in mongo

Below is a document from my database:
{
"_id" : ObjectId("58635ac32c9592064471cf5b"),
"agency_code" : "v5global",
"client_code" : "whirlpool",
"project_code" : "whirlpool",
"date" : {
"datetime" : 1464739200000.0,
"date" : 1464739200000.0,
"datejs" : ISODate("2016-06-01T00:00:00.000+0000"),
"datetimejs" : ISODate("2016-06-01T00:00:00.000+0000"),
"month" : NumberInt(5),
"year" : NumberInt(2016),
"day" : NumberInt(1)
},
"user" : {
"promoter_id" : NumberInt(19),
"promoter_name" : "Hira Singh Pawar",
"empcode" : "519230"
},
"counter" : {
"store_id" : NumberInt(4),
"store_name" : "Maya Sales ",
"chain_type" : "BS",
"address" : "6 Filamingo Market , Hissar",
"city" : "Hissar",
"state" : "Faridabad",
"region" : "North",
"sap_code" : "N_Far_91103948_1",
"unique_tp_code" : "91103948",
"location" : "6"
},
"insertedon" : {
"date" : 1464739200000.0,
"datejs" : ISODate("2016-06-01T00:00:00.000+0000"),
"datetimejs" : ISODate("2016-06-01T00:00:00.000+0000")
},
"insertedby" : "akshay",
"manager" : {
"manager_id" : NumberInt(5943),
"manager_name" : "Sonu Singh"
},
"type" : "display",
"data" : {
"brand" : "whirlpool",
"sku" : "60",
"model_name" : "Icemagic Fresh",
"sub_cat_name" : "DC",
"cat_name" : "Refrigerator",
"value" : NumberInt(1)
},
"IsDeleted" : false
}
I want to apply aggregation where I have to group it with city, state and region and if that counter has sold refrigerator I need that details in my result e.g if a counter has sold 2 refrigerators of whirlpool company then I want that to reflect in my result.
A counter can also sell other things like washing machines etc. So if they have sold 2 washing machines I want a result with { washingMachine: 2 }.
I have tried everything and nothing seems to be working here:
db.display_mop.aggregate( // Pipeline [
// Stage 1
{ $match: { "project_code":"whirlpool" } },
// Stage 2
{
$group: {
_id: {
"userid": "$user.promoter_id",
"userName": "$user.promoter_name",
"usercode": "$user.empcode",
"storename": "$counter.store_name",
"address": "$counter.address",
"city": "$counter.city",
"state": "$counter.state",
"region": "$counter.region"
}
}
},
],
// Options
{ allowDiskUse: true }

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();