Mongo/Mongoose - Find by partial document - node.js

I have a collection of properties that all have addresses.
"address" : {
"street" : "5 Orange Drive",
"city" : "Orlando",
"state" : {
"abbreviation" : "FL",
"name" : "Florida"
},
"zip" : "32822",
"geo" : {
"lat" : 28.519,
"lng" : -81.304
}
},
"address" : {
"street" : "16 Main Street",
"city" : "Tallahassee",
"state" : {
"abbreviation" : "FL",
"name" : "Florida"
},
"zip" : "32823",
"geo" : {
"lat" : 28.529,
"lng" : -81.314
}
},
"address" : {
"street" : "125 Oak Drive",
"city" : "Salem",
"state" : {
"abbreviation" : "MA",
"name" : "Massachusetts"
},
"zip" : "02108",
"geo" : {
"lat" : 24.519,
"lng" : -83.304
}
},
"address" : {
"street" : "96 Jones Way",
"city" : "Springfield",
"state" : {
"abbreviation" : "MA",
"name" : "Massachusetts"
},
"zip" : "01020",
"geo" : {
"lat" : 28.519,
"lng" : -84.304
}
},
"address" : {
"street" : "100 Sumner Ave",
"city" : "Springfield",
"state" : {
"abbreviation" : "IL",
"name" : "Illinois"
},
"zip" : "32822",
"geo" : {
"lat" : 22.519,
"lng" : -71.304
}
},
"address" : {
"street" : "40 Roger Ave",
"city" : "Salem",
"state" : {
"abbreviation" : "AL",
"name" : "Alabama"
},
"zip" : "32822",
"geo" : {
"lat" : 22.519,
"lng" : -71.304
}
}
I have an earlier query that returns an array of addresses such as:
[
{
name: 'Massachusetts - Salem',
city: 'Salem',
_id: 53784206cd73fbae193b62d5,
state: [Object]
}, {
name: 'Illinois - Springfield',
city: 'Springfield',
_id: 5376fa92bde0e0ea047e9abd,
state: [Object]
}
]
I would like to use the output of the above array to search the collection of properties by address.
Such as, I would like to search for all properties where the address contains a 'city of Springfield and a state of Illinois' and 'city of Salem and a state of Massachusetts'.
I was originally trying to do this using $in with some $and's mixed in but I wasn't sure if it was possible.

You could try using the $or operator on an array that contains query conditions derived from the other input array. For example, with the sample properties collection:
db.properties.insert([
{
"address" : {
"street" : "5 Orange Drive",
"city" : "Orlando",
"state" : {
"abbreviation" : "FL",
"name" : "Florida"
},
"zip" : "32822",
"geo" : {
"lat" : 28.519,
"lng" : -81.304
}
}
},
{
"address" : {
"street" : "16 Main Street",
"city" : "Tallahassee",
"state" : {
"abbreviation" : "FL",
"name" : "Florida"
},
"zip" : "32823",
"geo" : {
"lat" : 28.529,
"lng" : -81.314
}
}
},
{
"address" : {
"street" : "125 Oak Drive",
"city" : "Salem",
"state" : {
"abbreviation" : "MA",
"name" : "Massachusetts"
},
"zip" : "02108",
"geo" : {
"lat" : 24.519,
"lng" : -83.304
}
}
},
{
"address" : {
"street" : "96 Jones Way",
"city" : "Springfield",
"state" : {
"abbreviation" : "MA",
"name" : "Massachusetts"
},
"zip" : "01020",
"geo" : {
"lat" : 28.519,
"lng" : -84.304
}
}
},
{
"address" : {
"street" : "100 Sumner Ave",
"city" : "Springfield",
"state" : {
"abbreviation" : "IL",
"name" : "Illinois"
},
"zip" : "32822",
"geo" : {
"lat" : 22.519,
"lng" : -71.304
}
}
},
{
"address" : {
"street" : "40 Roger Ave",
"city" : "Salem",
"state" : {
"abbreviation" : "AL",
"name" : "Alabama"
},
"zip" : "32822",
"geo" : {
"lat" : 22.519,
"lng" : -71.304
}
}
}
])
The following query would give the desired result:
var res = [
{
"name": 'Massachusetts - Salem',
"city": 'Salem',
"_id": "53784206cd73fbae193b62d5",
"state": [{"name": "Massachusetts", "abbreviation": "MA"}]
}, {
"name": 'Illinois - Springfield',
"city": 'Springfield',
"_id": "5376fa92bde0e0ea047e9abd",
"state": [{"name": "Illinois", "abbreviation": "IL"}]
}
];
var condition = res.map(function (item){
return {
"address.city": item.city,
"address.state.name": item.state[0].name
}
});
db.properties.find({"$or": condition });
Sample Output
/* 0 */
{
"_id" : ObjectId("557848b43cab061ff5c618b7"),
"address" : {
"street" : "125 Oak Drive",
"city" : "Salem",
"state" : {
"abbreviation" : "MA",
"name" : "Massachusetts"
},
"zip" : "02108",
"geo" : {
"lat" : 24.519,
"lng" : -83.304
}
}
}
/* 1 */
{
"_id" : ObjectId("557848b43cab061ff5c618b9"),
"address" : {
"street" : "100 Sumner Ave",
"city" : "Springfield",
"state" : {
"abbreviation" : "IL",
"name" : "Illinois"
},
"zip" : "32822",
"geo" : {
"lat" : 22.519,
"lng" : -71.304
}
}
}

Related

How to update my address throug _id in myAddresses mongodb nodejs?

The data :
{
"_id" : ObjectId("5da6ea7228cc5e07b48173b5"),
"name" : "Joshi",
"email" : "joshiga#gmail.com",
"password" : "4emc8122",
"phone" : "60000000001",
"myAddresses" : [
{
"_id" : ObjectId("5da6eb511e21bf07ce33b868"),
"address" : "Office",
"firstName" : "joshi",
"lastName" : "g",
"country" : "India",
"city" : "VISAKHAPATNAM",
"province" : "Andhra Pradesh",
"postalCode" : 521344,
"phoneNumber" : 8100000006.0,
"address1" : "D.no:12,",
"address2" : "santhi nagar, gurudwara"
},
{
"_id" : ObjectId("5da6ec5e20a5db07da27fbc6"),
"address" : "Home",
"firstName" : "joshi",
"lastName" : "g",
"country" : "India",
"city" : "Vijayawada",
"province" : "Andhra Pradesh",
"postalCode" : 521333,
"phoneNumber" : 8000000006.0,
"address1" : "D.no:11-41,",
"address2" : "main road, kalidindi"
}
],
"__v" : 0
}
You can use the following:
CollectionName.update({'myAddresses._id': "Your ID"}, {'$set': {
'myAddresses.$. address': 'updated Address'
}}, function(err) { ...
ModelName.update({
"_id": req.params.id,
"myAddresses": {
"$elemMatch": {
"_id": req.params.addressId
}
}
}, {
$set: {
"myAddresses.$.address": req.body.address,
"myAddresses.$.firstName": firstName,
//add all fields
}
})

"How to get 'parent to child' relation with mongodb aggregation"

I have one collection called "location". in this collection all child and parent collection are stores. now I want to create a query who returns me parent to child spaces separated string.
Collection
businessId: { type: mongoose.Schema.Types.ObjectId, ref: 'admin' },
parentId: { type: mongoose.Schema.Types.ObjectId, ref: 'location' },
name: { type: String },
image: { type: String },
imageManipulation: { type: String },
locationColor: [{ range: { type: String }, color: { type: String } }],
area: {},
settings: {},
status: { type: String, enum: [0, 1], default: 1 },
isChild: { type: String, enum: [0, 1] },
parentPosition: { type: String }
In the above collection, you can see parentId field. if the location is a child then it have parentId. if the location is a parent then parentId will null. parent location can N level child location.
Collection Data
[{
"_id" : ObjectId("5cee1002a01ad50f5c222982"),
"status" : "1",
"name" : "Ground Floor",
"settings" : {
"zoom" : "0",
"positionX" : "0",
"positionY" : "0",
"width" : "498",
"height" : "498"
},
"image" : "1559105538977.jpg",
"businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor" : [],
"updatedAt" : ISODate("2019-05-29T04:52:18.999Z"),
"createdAt" : ISODate("2019-05-29T04:52:18.999Z"),
"__v" : 0
},
{
"_id" : ObjectId("5cee103ca01ad50f5c222983"),
"status" : "1",
"name" : "Kitchen",
"settings" : {
"zoom" : "0",
"positionX" : "0",
"positionY" : "0",
"width" : "498",
"height" : "498"
},
"area" : "{\"type\":3,\"points\":[{\"x\":20,\"y\":178},{\"x\":19,\"y\":75},{\"x\":56,\"y\":71},{\"x\":57,\"y\":52},{\"x\":80,\"y\":18},{\"x\":138,\"y\":17},{\"x\":165,\"y\":52},{\"x\":165,\"y\":94},{\"x\":174,\"y\":96},{\"x\":173,\"y\":179}],\"fill\":\"rgba(178,40,40,0.58)\"}",
"parentId" : ObjectId("5cee1002a01ad50f5c222982"),
"image" : "1559105596975.jpg",
"businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor" : [],
"updatedAt" : ISODate("2019-05-29T04:53:16.990Z"),
"createdAt" : ISODate("2019-05-29T04:53:16.990Z"),
"__v" : 0
},
{
"_id" : ObjectId("5cee1078a01ad50f5c222984"),
"status" : "1",
"name" : "Cbot",
"settings" : {
"zoom" : "0",
"positionX" : "0",
"positionY" : "0",
"width" : "498",
"height" : "498"
},
"area" : "{\"type\":3,\"points\":[{\"x\":20,\"y\":311},{\"x\":17,\"y\":59},{\"x\":84,\"y\":58},{\"x\":88,\"y\":312}],\"fill\":\"rgba(20,205,123,0.67)\"}",
"parentId" : ObjectId("5cee103ca01ad50f5c222983"),
"image" : "1559105656049.jpg",
"businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor" : [],
"updatedAt" : ISODate("2019-05-29T04:54:16.070Z"),
"createdAt" : ISODate("2019-05-29T04:54:16.070Z"),
"__v" : 0
},
{
"_id" : ObjectId("5cee10c1a01ad50f5c222985"),
"status" : "1",
"name" : "Drower 1",
"settings" : {
"zoom" : "5",
"positionX" : "470",
"positionY" : "70",
"width" : "498",
"height" : "498"
},
"area" : "{\"type\":3,\"points\":[{\"x\":21,\"y\":102},{\"x\":81,\"y\":104},{\"x\":79,\"y\":43},{\"x\":21,\"y\":43}],\"fill\":\"rgba(16,77,193,0.5)\"}",
"parentId" : ObjectId("5cee1078a01ad50f5c222984"),
"image" : "1559105729881.jpg",
"businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor" : [],
"updatedAt" : ISODate("2019-05-29T04:55:29.901Z"),
"createdAt" : ISODate("2019-05-29T04:55:29.901Z"),
"__v" : 0
},
{
"_id" : ObjectId("5cee110ea01ad50f5c222986"),
"status" : "1",
"name" : "Drawer 2",
"settings" : {
"zoom" : "5",
"positionX" : "484",
"positionY" : "103",
"width" : "498",
"height" : "498"
},
"area" : "{\"type\":1,\"coordinates\":{\"x\":23,\"y\":125,\"width\":58,\"height\":56},\"points\":[{\"x\":23,\"y\":125},{\"x\":81,\"y\":181}],\"fill\":\"rgba(117,37,109,0.74)\"}",
"parentId" : ObjectId("5cee1078a01ad50f5c222984"),
"image" : "1559105806551.jpg",
"businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor" : [],
"updatedAt" : ISODate("2019-05-29T04:56:46.574Z"),
"createdAt" : ISODate("2019-05-29T04:56:46.574Z"),
"__v" : 0
},
{
"_id" : ObjectId("5cee1148a01ad50f5c222987"),
"status" : "1",
"name" : "Drawer 3",
"settings" : {
"zoom" : "5",
"positionX" : "477",
"positionY" : "94",
"width" : "498",
"height" : "498"
},
"area" : "{\"type\":3,\"points\":[{\"x\":22,\"y\":205},{\"x\":20,\"y\":290},{\"x\":84,\"y\":288},{\"x\":85,\"y\":205}],\"fill\":\"rgba(164,108,54,0.57)\"}",
"parentId" : ObjectId("5cee1078a01ad50f5c222984"),
"image" : "1559105864947.jpg",
"businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor" : [],
"updatedAt" : ISODate("2019-05-29T04:57:44.972Z"),
"createdAt" : ISODate("2019-05-29T04:57:44.972Z"),
"__v" : 0
},
{
"_id" : ObjectId("5cee5e683b9f67a9f501f818"),
"status" : "1",
"name" : "Washroom",
"settings" : {
"zoom" : "5",
"positionX" : "477",
"positionY" : "94",
"width" : "498",
"height" : "498"
},
"area" : "{\"type\":3,\"points\":[{\"x\":22,\"y\":205},{\"x\":20,\"y\":290},{\"x\":84,\"y\":288},{\"x\":85,\"y\":205}],\"fill\":\"rgba(164,108,54,0.57)\"}",
"parentId" : ObjectId("5cee1002a01ad50f5c222982"),
"image" : "1559105864947.jpg",
"businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor" : [],
"updatedAt" : ISODate("2019-05-29T04:57:44.972Z"),
"createdAt" : ISODate("2019-05-29T04:57:44.972Z"),
"__v" : 0
},
{
"_id" : ObjectId("5cee5f593b9f67a9f501fa01"),
"status" : "1",
"name" : "Third Floor",
"settings" : {
"zoom" : "0",
"positionX" : "0",
"positionY" : "0",
"width" : "498",
"height" : "498"
},
"image" : "1559105538977123.jpg",
"businessId" : ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor" : [],
"updatedAt" : ISODate("2019-05-29T04:52:18.999Z"),
"createdAt" : ISODate("2019-05-29T04:52:18.999Z"),
"__v" : 0
}]
Expected result in JSON
[
{
"_id": "5cee1002a01ad50f5c222982",
"name": "Ground Floor"
},
{
"_id": "5cee103ca01ad50f5c222983",
"name": " Kitchen"
},
{
"_id": "5cee1078a01ad50f5c222984",
"name": " Cbot"
},
{
"_id": "5cee110ea01ad50f5c222986",
"name": " Drawer 2"
},
{
"_id": "5cee1148a01ad50f5c222987",
"name": " Drawer 3"
},
{
"_id": "5cee10c1a01ad50f5c222985",
"name": " Drower 1"
},
{
"_id": "5cee5e683b9f67a9f501f818",
"name": " Washroom"
},
{
"_id": "5cee5f593b9f67a9f501fa01",
"name": "Third Floor"
}
]
I do not think you should let mongodb take care of name formatting. So my solution is about finding how many spaces a certain name needs before, so that js can deal with formatting. This is the query:
db.collection.aggregate([
{
$graphLookup: {
from: "collection",
startWith: "$parentId",
connectFromField: "parentId",
connectToField: "_id",
as: "hierarchy"
}
},
{
$project: {
"_id": 1,
"name": 1,
"hierarchy_size": { $size: "$hierarchy" }
}
}
]);
With the $graphLookup, the db is building an in memory graph of edges between connectFromField and connectToField. From the graph you only need the depth of your hierarchy, so I computed hierarchy_size. This is the output:
/* 1 */
{
"_id" : ObjectId("5cee1002a01ad50f5c222982"),
"name" : "Ground Floor",
"hierarchy_size" : 0
}
/* 2 */
{
"_id" : ObjectId("5cee103ca01ad50f5c222983"),
"name" : "Kitchen",
"hierarchy_size" : 1
}
/* 3 */
{
"_id" : ObjectId("5cee1078a01ad50f5c222984"),
"name" : "Cbot",
"hierarchy_size" : 2
}
/* 4 */
{
"_id" : ObjectId("5cee10c1a01ad50f5c222985"),
"name" : "Drower 1",
"hierarchy_size" : 3
}
/* 5 */
{
"_id" : ObjectId("5cee110ea01ad50f5c222986"),
"name" : "Drawer 2",
"hierarchy_size" : 3
}
/* 6 */
{
"_id" : ObjectId("5cee1148a01ad50f5c222987"),
"name" : "Drawer 3",
"hierarchy_size" : 3
}
/* 7 */
{
"_id" : ObjectId("5cee5e683b9f67a9f501f818"),
"name" : "Washroom",
"hierarchy_size" : 1
}
/* 8 */
{
"_id" : ObjectId("5cee5f593b9f67a9f501fa01"),
"name" : "Third Floor",
"hierarchy_size" : 0
}
The only problem here might be query performances, but that depends on how much data you need to process. Also consider the memory limit.

how to write a mongodb aggregation query for following description

I need a query for:
whose userids are : "userId" : "111b/c", "userId" : "111a". based on the user ids how many are $eq:light_pad:20 with them i need userId:111b/c-max date,userId:111a-max date
DB data
{ "_id" : ObjectId("5a7c1d167826eaca4b4e4398"), "firstName" : "varun", "secName" : "raju", "userId" : "111a", "light_pad" : "20", "lights" : "on", "CREATE_DATE" : ISODate("2018-05-08T03:12:00Z"), "Department" : "Computer Science and Engg", "Percentage" : "76%", "Address" : { "Street" : "Burkit Road", "City" : "chennai", "State" : "Tamil Nadu" }, "Gender" : "Male" }
{ "_id" : ObjectId("5a7c1db77826eaca4b4e4399"), "firstName" : "raju", "secName" : "rani", "userId" : "111a", "light_pad" : "40", "lights" : "off", "CREATE_DATE" : ISODate("2017-04-08T03:12:00Z"), "Department" : "Computer Science and Engg", "Percentage" : "86%", "Address" : { "Street" : "Burkit Road", "City" : "chennai", "State" : "Tamil Nadu" }, "Gender" : "female" }
{ "_id" : ObjectId("5a7c1e707826eaca4b4e439b"), "firstName" : "ranga", "secName" : "mahesh", "userId" : "111a", "light_pad" : "26", "lights" : "on", "CREATE_DATE" : ISODate("2012-04-08T03:12:00Z"), "Department" : "Computer Science and Engg", "Percentage" : "7%", "Address" : { "Street" : "Burkit ", "City" : "vizag", "State" : "Tamil Nadu" }, "Gender" : "female" }
{ "_id" : ObjectId("5a7c1f5d7826eaca4b4e439d"), "firstName" : "kalu", "secName" : "ramana", "userId" : "111b/c", "light_pad" : "25", "lights" : "off", "CREATE_DATE" : ISODate("2014-06-08T03:12:00Z"), "Department" : "maths", "Percentage" : "46%", "Address" : { "Street" : "Burkit ", "City" : "bhimavaram", "State" : "Tamil Nadu" }, "Gender" : "male" }
{ "_id" : ObjectId("5a7c1fb37826eaca4b4e439e"), "firstName" : "praveen", "secName" : "pani", "userId" : "111b/c", "light_pad" : "52", "lights" : "on", "CREATE_DATE" : ISODate("2016-06-08T03:12:00Z"), "Department" : "maths", "Percentage" : "36%", "Address" : { "Street" : "vin ", "City" : "palakoderu", "State" : "Tamil Nadu" }, "Gender" : "male" }
{ "_id" : ObjectId("5a7c20057826eaca4b4e439f"), "firstName" : "vani", "secName" : "karun", "userId" : "111b/c", "light_pad" : "52", "lights" : "on", "CREATE_DATE" : ISODate("2013-06-08T03:12:00Z"), "Department" : "maths", "Percentage" : "76%", "Address" : { "Street" : "bali ", "City" : "srikakulam", "State" : "Tamil Nadu" }, "Gender" : "male" }
Any answer will be appreciated
Thanks in advance.
I don't understand your question properly, but I have a solution that could be related to your question. I hope it will help you.
db.test.aggregate([{
$match: {
_id: {
$in: [ObjectId("5a7c1d167826eaca4b4e4398"),
ObjectId("5a7c1db77826eaca4b4e4399")]
},
light_pad: {
$eq: "20"
}
}
}]);
It will gives the given result:
{
"_id" : ObjectId("5a7c1d167826eaca4b4e4398"),
"firstName" : "varun",
"secName" : "raju",
"userId" : "111a",
"light_pad" : "20",
"lights" : "on",
"CREATE_DATE" : ISODate("2018-05-08T03:12:00.000Z"),
"Department" : "Computer Science and Engg",
"Percentage" : "76%",
"Address" : {
"Street" : "Burkit Road",
"City" : "chennai",
"State" : "Tamil Nadu"
},
"Gender" : "Male"
}

Adding document under nested documents

I need to add one more address like address.2._id,type,etc...:
{
"address" : {
"1" : {
"_id" : ObjectId("5a570f3d422c8223bac22dca"),
"type" : "Primary",
"street" : "58,Jones road",
"area" : "Saidapet",
"city" : "Chennai",
"pincode" : "600015",
"state" : "Tamil nadu",
"country" : "India"
}
}
}
How do I insert a particular document under a nested document?

Mongodb Count multiple subobjects and group by

Hello This query is running fine for me I want to add other arrays as well like contact and I want separate count for them. If I add contact it add the result in count P.S : I used array name with $sum it start showing me zero count
return Company.aggregate(
{"$unwind":"$agreement"},
{"$unwind":"$contact"},
{"$unwind":"$companySite"},
{ $group: { _id: {
"Organization": "$orgId",
"Company": "$name"
}, "count": { $sum: 1 } } },{
"$project": {
"_id": 0,
"Company": "$_id.Company",
"Organization":"$_id.Organization",
"Count": "$count"
}
})
expected output
"Company": "Multi-Metal Manufacturing",
"Organization": "1",
"AgreementCount": 1,
"ContactCount" : 4
"ABC Count": 5
Sample Document is :
{
"_id" : ObjectId("57c6a97a90c933a2d54117dc"),
"ITBCompanyId" : 1034,
"updatedAt" : ISODate("2016-08-31T12:47:03.679Z"),
"createdAt" : ISODate("2016-08-31T09:55:06.217Z"),
"identifier" : "INL10",
"name" : "Inline Data Systems",
"addressLine1" : "7 Park Place",
"addressLine2" : "Ste D",
"city" : "Swansea",
"orgId" : "1",
"deletedAt" : null,
"_info" : {
"lastUpdated" : ISODate("2016-02-10T21:22:15.000Z"),
"updatedBy" : "Clarissa"
},
"whois" : [],
"configuration" : [],
"contact" : [
{
"email" : "justin#inlinedatasystems.com",
"mobileGuid" : "d8852942-8f5a-406f-a646-a5f8697f7885",
"presence" : null,
"gender" : null,
"title" : null,
"country" : null,
"zip" : null,
"state" : null,
"city" : null,
"addressLine2" : null,
"addressLine1" : null,
"lastName" : "Wilkerson",
"firstName" : "Justin",
"id" : 191,
"_id" : ObjectId("57c6abdfb966968130b1671c"),
"communicationItems" : [],
"customFields" : null,
"company" : {
"name" : "Inline Data Systems",
"id" : "19331"
},
"relationship" : {
"name" : null,
"id" : 0
}
}
],
"agreement" : [
{
"periodType" : null,
"billAmount" : "0",
"billTermsId" : 12,
"billOneTimeFlag" : false,
"billCycleId" : "2",
"expiredDays" : "0"
},
{
"id" : "40",
"name" : "Managed Hosted Server Agreement",
"billAmount" : "0",
"periodType" : null,
"_id" : ObjectId("57c6ab96b966968130b16616"),
"_info" : {
"lastUpdated" : ISODate("2014-10-03T14:25:42.000Z"),
"updatedBy" : "ali "
},
"contact" : {
"id" : "191",
"name" : "Justin Wilkerson"
},
"agreementType" : {
"id" : "33",
"name" : "HDCloud - Hosted Server"
}
},
{
"id" : "41",
"name" : "Managed Backup Agreement",
"parentAgreementId" : "42",
"customerPO" : ""
}
],
"companySite" : [
{
"id" : 1037,
"name" : "Main",
"city" : "Swansea",
"state" : "IL",
"zip" : "62226",
}
]

Resources