Mongodb filter results with unique value - node.js

I have a collections of bunch of cities and zip codes, where name of a city can be a same, while zip code is different.
I'm trying to query thru all cities starting with 'San' for example and want to filter results where San Antonio appears only ones along with any other cities starting with San.
Here is a code I use:
Zipcodes.find(
{ city: { $regex: /San/, $options: 'i' } },
(err, result) => {
if (err) {
return res.send({ error: err });
}
res.send({ data: result });
},
).limit(20);
This given me following results:
{
"loc": [
-94.132581,
31.515173
],
"_id": "75972",
"city": "SAN AUGUSTINE",
"pop": 5916,
"state": "TX"
},
{
"loc": [
-98.730929,
31.162678
],
"_id": "76877",
"city": "SAN SABA",
"pop": 4023,
"state": "TX"
},
{
"loc": [
-100.481752,
31.478165
],
"_id": "76901",
"city": "SAN ANGELO",
"pop": 23800,
"state": "TX"
},
{
"loc": [
-100.480036,
31.419411
],
"_id": "76904",
"city": "SAN ANGELO",
"pop": 25535,
"state": "TX"
},
{
"loc": [
-100.390005,
31.464738
],
"_id": "76905",
"city": "SAN ANGELO",
"pop": 11284,
"state": "TX"
},
{
"loc": [
-100.438586,
31.470735
],
"_id": "76903",
"city": "SAN ANGELO",
"pop": 32471,
"state": "TX"
},
{
"loc": [
-95.034496,
29.466033
],
"_id": "77539",
"city": "SAN LEON",
"pop": 21905,
"state": "TX"
},
{
"loc": [
-99.427148,
27.062523
],
"_id": "78067",
"city": "SAN YGNACIO",
"pop": 871,
"state": "TX"
},
{
"loc": [
-98.460127,
29.414799
],
"_id": "78203",
"city": "SAN ANTONIO",
"pop": 7261,
"state": "TX"
},
{
"loc": [
-98.525967,
29.422855
],
"_id": "78207",
"city": "SAN ANTONIO",
"pop": 58355,
"state": "TX"
},
{
"loc": [
-98.5063,
29.400217
],
"_id": "78204",
"city": "SAN ANTONIO",
"pop": 11526,
"state": "TX"
},
{
"loc": [
-98.479338,
29.441338
],
"_id": "78215",
"city": "SAN ANTONIO",
"pop": 1264,
"state": "TX"
},
{
"loc": [
-98.545219,
29.358366
],
"_id": "78211",
"city": "SAN ANTONIO",
"pop": 30417,
"state": "TX"
},
{
"loc": [
-98.492509,
29.423711
],
"_id": "78205",
"city": "SAN ANTONIO",
"pop": 1714,
"state": "TX"
},
{
"loc": [
-98.497511,
29.533387
],
"_id": "78216",
"city": "SAN ANTONIO",
"pop": 30435,
"state": "TX"
},
{
"loc": [
-98.419444,
29.539525
],
"_id": "78217",
"city": "SAN ANTONIO",
"pop": 27925,
"state": "TX"
}
It's returning San Antonio many times. I need only ones.
Please help with a correct query. Thanks.

You can use $group + $replaceRoot to get values unique by city:
db.collection.aggregate([
{
$match: { city: { $regex: "San", $options: "i" } }
},
{
$group: {
_id: "$city",
doc: { $first: "$$ROOT" }
}
},
{
$replaceRoot: {
newRoot: "$doc"
}
}
])
Mongo Playground

Related

How to filter the response from mongoDB, so nested arrays will include only items that meet a condition?

My documents look like this
{
"_id": {
"$oid": "62825f71005ce00c5f0235c1"
},
"user": "jon",
"roles": {
"User": 2001,
},
"STOCK ": [
{
"sku": "BLACK-M",
"productname": "BLACK",
"sendout": 0,
"recived": 1,
"totalinstock": 40,
"location": "B32",
"_id": {
"$oid": "62826016005ce00c5f0235c8"
}
},
{
"sku": "CJNS",
"productname": "89796363",
"sendout": 0,
"recived": 45,
"totalinstock": 0,
"location": "B232",
"_id": {
"$oid": "62836f2d56b4f1ac79c99b8d"
}
}
],
"ORDERS": [
{
"date": {
"$date": "2022-06-02T15:23:58Z"
},
"OrderNumber": "745607",
"City": "xxxxx",
"Address": "yyyyyy",
"Phone": "8678678678",
"Name": "Holly ",
"Trackingnumber": 40,
"ZipCode": 00000,
"Province": "New ",
"Quantity": [
1
],
"Product_Name": [
" pants pants"
],
"SKU": [
"CJNS"
],
"_id": {
"$oid": "6298d61ba6eeec72b78332a7"
}
},
{
"date": {
"$date": "2022-06-02T15:23:58Z"
},
"OrderNumber": "748840",
"City": "xxxxx",
"Address": "yyyyyy",
"Phone": "354353454",
"Name": "Michael",
"Trackingnumber": 0,
"ZipCode": 00000,
"Province": "North",
"Quantity": [
1
],
"Product_Name": [
" pants pants"
],
"SKU": [
"CJNS"
],
"_id": {
"$oid": "6298d61ba6eeec72b78332a9"
}
}
]
}
I successful to return all the objects in STOCK or all the objects in ORDERS
Through this query
const foundUser= await User.find({"user":req.body.user},("Orders") ).exec()
Now I want to filter the response to include only items where "Trackingnumber" is different from 0
For the sample data I expect to receive only
{
"date": {
"$date": "2022-06-02T15:23:58Z"
},
"OrderNumber": "748840",
"City": "xxxxx",
"Address": "yyyyyy",
"Phone": "354353454",
"Name": "Michael",
"Trackingnumber": 0,
"ZipCode": 00000,
"Province": "North",
"Quantity": [
1
],
"Product_Name": [
" pants pants"
],
"SKU": [
"CJNS"
],
"_id": {
"$oid": "6298d61ba6eeec72b78332a9"
}
}
You can use an aggregation pipeline with a $filter for this:
db.collection.aggregate([
{
$match: {
"user": "jon"
}
},
{
$project: {
ORDERS: {
$filter: {
input: "$ORDERS",
as: "item",
cond: {$ne: ["$$item.Trackingnumber", 0]}
}
}
}
}
])
Playground example
User.find({"Orders" : {"Trackingnumber": 0} })

Loadrunner json parser

Requirement- from below code snippet, i need to pull data related to market segment= unicare.
in the subsequent request need to pass both state and market segment unicare..
first i need to find do i see unicare market segement.. if Yes what is the first occurance and its associated state. to be captured and placed in the consequent request.
tried lr_json_get_values. can you please help on this.
{
"taxID": "23424",
"firstName": "afsafa",
"lastName": "asdfsfa",
"middleName": "adfasad",
"npn": "324322424",
"stateResident": "WI",
"dateBirth": "234324224",
"licenseDetails": [
{
"state": "CO",
"license": [
{
"licenseNum": "3234224",
"dateUpdated": "12/08/2020",
"dateIssueLicenseOrg": "324242",
"dateExpireLicense": "243242",
"licenseClass": "avadfa Producer",
"licenseClassCode": "2",
"residencyStatus": "444",
"active": "Yes",
"details": [
{
"loa": "aafafafa",
"loaCode": "44444",
"authorityIssueDate": "44345353",
"status": "Active",
"statusReasonDate": "444444",
"ceCompliance": "N/S",
"ceCreditsNeeded": "0"
}
]
}
],
"address": [
{
"dateUpdated": "423333",
"addressTypeCode": "2",
"addrType": "adfafa",
"addrLine1": "asssss",
"nameCity": "aaaa",
"nameState": "WI",
"zip": "4444444",
"country": "U.S.A."
},
{
"dateUpdated": "10/22/2020",
"addressTypeCode": "2",
"addrType": "adfafa",
"addrLine1": "Fhk sfsfsafs",
"addrLine2": "6sdfsfsfa Ave",
"nameCity": "dfsafa",
"nameState": "WI",
"zip": "sdfsaff",
"country": "U.S.A."
},
{
"dateUpdated": "45353",
"addressTypeCode": "1",
"addrType": "45adfa",
"addrLine1": "1sfsafaf",
"nameCity": "adfafafa",
"nameState": "WI",
"zip": "34444-434",
"country": "U.S.A."
}
],
"brands": [
"ALWAYS"
],
"marketSegment": [
{
"brandName": "ALWAYS",
"lobTypes": [
"Individual",
"Senior"
]
},
{
"brandName": "Unicare",
"lobTypes": [
"Individual",
"Senior",
"Small Group",
"Large Group"
]
}
],
"isLifeExists": false
},
{
"state": "FL",
"license": [
{
"licenseNum": "3234224",
"dateUpdated": "12/08/2020",
"dateIssueLicenseOrg": "324242",
"dateExpireLicense": "243242",
"licenseClass": "avadfa Producer",
"licenseClassCode": "2",
"residencyStatus": "444",
"active": "Yes",
"details": [
{
"loa": "aafafafa",
"loaCode": "44444",
"authorityIssueDate": "44345353",
"status": "Active",
"statusReasonDate": "444444",
"ceCompliance": "N/S",
"ceCreditsNeeded": "0"
}
]
}
],
"address": [
{
"dateUpdated": "423333",
"addressTypeCode": "2",
"addrType": "adfafa",
"addrLine1": "asssss",
"nameCity": "aaaa",
"nameState": "WI",
"zip": "4444444",
"country": "U.S.A."
},
{
"dateUpdated": "10/22/2020",
"addressTypeCode": "2",
"addrType": "adfafa",
"addrLine1": "Fhk sfsfsafs",
"addrLine2": "6sdfsfsfa Ave",
"nameCity": "dfsafa",
"nameState": "WI",
"zip": "sdfsaff",
"country": "U.S.A."
},
{
"dateUpdated": "45353",
"addressTypeCode": "1",
"addrType": "45adfa",
"addrLine1": "1sfsafaf",
"nameCity": "adfafafa",
"nameState": "WI",
"zip": "34444-434",
"country": "U.S.A."
}
],
"brands": [],
"marketSegment": [
{
"brandName": "Unicare",
"lobTypes": [
"Individual",
"Senior",
"Small Group",
"Large Group"
]
}
],
"isLifeExists": false
},
{
"state": "WI",
"license": [
{
"licenseNum": "3234224",
"dateUpdated": "12/08/2020",
"dateIssueLicenseOrg": "324242",
"dateExpireLicense": "243242",
"licenseClass": "avadfa Producer",
"licenseClassCode": "2",
"residencyStatus": "444",
"active": "Yes",
"details": [
{
"loa": "aafafafa",
"loaCode": "44444",
"authorityIssueDate": "44345353",
"status": "Active",
"statusReasonDate": "444444",
"ceCompliance": "N/S",
"ceCreditsNeeded": "0"
}
]
}
],
"address": [
{
"dateUpdated": "423333",
"addressTypeCode": "2",
"addrType": "adfafa",
"addrLine1": "asssss",
"nameCity": "aaaa",
"nameState": "WI",
"zip": "4444444",
"country": "U.S.A."
},
{
"dateUpdated": "10/22/2020",
"addressTypeCode": "2",
"addrType": "adfafa",
"addrLine1": "Fhk sfsfsafs",
"addrLine2": "6sdfsfsfa Ave",
"nameCity": "dfsafa",
"nameState": "WI",
"zip": "sdfsaff",
"country": "U.S.A."
},
{
"dateUpdated": "45353",
"addressTypeCode": "1",
"addrType": "45adfa",
"addrLine1": "1sfsafaf",
"nameCity": "adfafafa",
"nameState": "WI",
"zip": "34444-434",
"country": "U.S.A."
}
],
"brands": [
"ALWAYS",
"WCICWCICsd(sdfsafasdfsa COLLABORATIVE sdfsfsdf COMP)"
],
"marketSegment": [
{
"brandName": "ALWAYS",
"lobTypes": [
"Individual",
"Senior",
"Small Group",
"Large Group"
]
},
{
"brandName": "WCICsd(sdfsafasdfsa COLLABORATIVE sdfsfsdf COMP)",
"lobTypes": [
"Individual",
"Small Group",
"Large Group"
]
},
{
"brandName": "Unicare",
"lobTypes": [
"Individual",
"Senior",
"Small Group",
"Large Group"
]
}
],
"isLifeExists": true
}
]
}

convert to asc order of array data using MongoDB

how to make this data to asc order by user's first name and user's last name.
I got the response, want to sort the records by user's first name but it is taking from creation date I guess when using sort how can I make it base on user's first name and user's last name please guide
{
"response": {
"items": [
{
"_id": "5e71f86bd300b313df52fb2f",
"last_message": {
"text": "Alex",
"users": [
{
"_id": "5e4a8d2d3952132a08ae5764",
"first_name": "zack",
"last_name": "Write"
}
]
},
"texter": [
"alex",
"$0ctg"
],
"title": "New group1",
"group": true,
"members": [
{
"_id": "5e4a8afc3952132a08ae575e",
"first_name": "test3",
"last_name": "test4"
}
],
"managers": [
"5e4a8afc3952132a08ae575e"
],
"member": {
"_id": "5e4a8afc3952132a08ae575e",
"first_name": "test3",
"last_name": "test4"
}
},
{
"_id": "5e4e740f380054797d9db621",
"last_message": {
"text": "",
"users": [
{
"_id": "5e4a8d2d3952132a08ae5764",
"first_name": "yuhan",
"last_name": "jacob"
}
]
},
"texter": [
"",
"",
"",
"",
"",
"new iphone x\n brand new iphone wv wwvqzwzvq had sqswgscq wow you wholeheartedly q \n $600.00",
"helo",
"hello",
"hi"
],
"members": [
{
"_id": "5e4d0973babf2b74ca868f4d",
"first_name": "alex",
"last_name": "hales"
}
],
"managers": [],
"member": {
"_id": "5e4d0973babf2b74ca868f4d",
"first_name": "alex",
"last_name": "hales"
}
}
]
}
}
Tried
{
$sort: {
users: 1,
}
},
doesn't help much
Also if I would like to add two field asc desc order what would be the process in MongoDB
Try this hope this will help you !
{
$sort: { "users.first_name": 1 }
},

How to setup Partial Authentication using Authorize API

Okay I am setting up Partial Payments via the Authorize.net API in order to enable multiple cards to be used to cover a single balance/charge.
I'm assuming thier Partial Auth feature covers my use case, but in testing, there is an issue I can show you using the API live console here: https://developer.authorize.net/api/reference/index.html#payment-transactions-charge-a-credit-card
Go to the link above and authorize partial payments with the request I edited below and you will notice when you press submit you get a splitTenderId:
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "5KP3u95bQpv",
"transactionKey": "346HZ32z3fP4hTG2"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "462.25",
"payment": {
"creditCard": {
"cardNumber": "5424000000000015",
"expirationDate": "2020-12",
"cardCode": "999"
}
},
"lineItems": {
"lineItem": {
"itemId": "1",
"name": "vase",
"description": "Cannes logo",
"quantity": "18",
"unitPrice": "45.00"
}
},
"tax": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"duty": {
"amount": "8.55",
"name": "duty name",
"description": "duty description"
},
"shipping": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"poNumber": "456654",
"customer": {
"id": "99999456654"
},
"billTo": {
"firstName": "Ellen",
"lastName": "Johnson",
"company": "Souveniropolis",
"address": "14 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"shipTo": {
"firstName": "China",
"lastName": "Bayles",
"company": "Thyme for Tea",
"address": "12 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"customerIP": "192.168.1.1",
"transactionSettings": {
"setting": [
{
"settingName": "emailCustomer",
"settingValue": "true"
}, {
"settingName": "allowPartialAuth",
"settingValue": "true"
},
]
},
"userFields": {
"userField": [
{
"name": "MerchantDefinedFieldName1",
"value": "MerchantDefinedFieldValue1"
},
{
"name": "favorite_color",
"value": "blue"
}
]
}
}
}
}
This is only successful because the amount is 462.25 as the docs say to use for testing, if I use any other (real) amount the splitTenderId is not there.
Here is a new example request, you can post this again on the link above:
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "5KP3u95bQpv",
"transactionKey": "346HZ32z3fP4hTG2"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "462",
"payment": {
"creditCard": {
"cardNumber": "5424000000000015",
"expirationDate": "2020-12",
"cardCode": "999"
}
},
"lineItems": {
"lineItem": {
"itemId": "1",
"name": "vase",
"description": "Cannes logo",
"quantity": "18",
"unitPrice": "45.00"
}
},
"tax": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"duty": {
"amount": "8.55",
"name": "duty name",
"description": "duty description"
},
"shipping": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"poNumber": "456654",
"customer": {
"id": "99999456654"
},
"billTo": {
"firstName": "Ellen",
"lastName": "Johnson",
"company": "Souveniropolis",
"address": "14 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"shipTo": {
"firstName": "China",
"lastName": "Bayles",
"company": "Thyme for Tea",
"address": "12 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"customerIP": "192.168.1.1",
"transactionSettings": {
"setting": [
{
"settingName": "emailCustomer",
"settingValue": "true"
}, {
"settingName": "allowPartialAuth",
"settingValue": "true"
},
]
},
"userFields": {
"userField": [
{
"name": "MerchantDefinedFieldName1",
"value": "MerchantDefinedFieldValue1"
},
{
"name": "favorite_color",
"value": "blue"
}
]
}
}
}
}
And with the 462 amount entered this is no longer a partial auth payment and I no longer get a splitTenderId.
Can someone please help me figure out what is going on?

Reshaping Documents in $project Stages

For our collection which looks like this:
> db.companies.find().limit(1).pretty() {
"_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 <a href=\"/company/zoho-manageengine\"
title=\"Zoho ManageEngine\" rel=\"nofollow\">Zoho ManageEngine</a>.</p>\n\n<p>F
ounded in 1996, AdventNet has served a diverse range of enterprise IT, networkin
g and telecom customers.</p>\n\n<p>AdventNet supplies server and network managem
ent software.</p>",
"image": {
"available_sizes": [
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-150
x150.png"
],
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-250
x250.png"
],
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-450
x450.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": []
} >
For the below query for our node.js app.
db.companies.aggregate([{
$match: {
"name": "Facebook"
},
$project: {
"_id": 0,
"name": 1,
"people": "$relationships.person.last_name"
}
}])
Gives the following error:
assert: command failed: {
"ok" : 0,
"errmsg" : "A pipeline stage specification object must contain exactly o ne field.",
"code" : 16435 } : aggregate failed
_getErrorWithCode#src/mongo/shell/utils.js:25:13 doassert#src/mongo/shell/assert.js:13:14
assert.commandWorked#src/mongo/shell/assert.js:267:5
DBCollection.prototype.aggregate#src/mongo/shell/collection.js:1312:5
#(shell):1:1
2016-09-17T19:20:26.303+0530 E QUERY [thread1] Error: command
failed: {
"ok" : 0,
"errmsg" : "A pipeline stage specification object must contain exactly o ne field.",
"code" : 16435 } : aggregate failed :
_getErrorWithCode#src/mongo/shell/utils.js:25:13 doassert#src/mongo/shell/assert.js:13:14
assert.commandWorked#src/mongo/shell/assert.js:267:5
DBCollection.prototype.aggregate#src/mongo/shell/collection.js:1312:5
#(shell):1:1
I'm unable to figure out why?
You are missing some braces for your aggregation pipeline operators. The correct pipeline should be:
db.companies.aggregate([
{ "$match": { "name": "Facebook" } }, /* match pipeline stage */
{ "$project": { /* project pipeline stage */
"_id": 0,
"name": 1,
"people": "$relationships.person.last_name"
} }
])

Resources