高橋  陽子

高橋 陽子

1659958380

深入了解 JavaScript 的排序方法

.sort(...)方法提供了一種以聲明方式對數組進行排序的簡單方法,只需指定任何兩個元素應如何相互排序。雖然對字符串數組進行排序非常簡單,但您可能會在嘗試對其他類型的數據進行排序時發現一些問題。在本文中,我們將看到幾個“秘訣”,它們將使您能夠以最少的編碼實現所有類型的排序過程!

讓我們回顧一下基本概念。要對某個數組進行排序,請編寫someArray.sort(comparisonFn); comparisonFn是一個接收兩個元素a和的函數,如果應該先於,b則返回負值,如果應該跟隨,則返回正值,如果和相等則返回零。要完成更困難的排序任務,關鍵是編寫適當的比較函數,這就是我們將在下面看到的。ababab

對字符串進行排序

使用.sort(...)字符串數組很簡單,因為您根本不需要做任何事情!如果未提供任何函數,則通過比較數組值的字符串表示來進行排序。

const zodiac = [
  "Aries",
  "Taurus",
  "Gemini",
  "Cancer",
  "Leo",
  "Virgo",
  "Libra",
  "Scorpio",
  "Sagittarius",
  "Capricorn",
  "Aquarius",
  "Pisces"
];

zodiac.sort();
/*
[
 "Aquarius", "Aries", "Cancer", "Capricorn", 
 "Gemini", "Leo", "Libra", "Pisces", 
 "Sagittarius", "Scorpio", "Taurus", "Virgo"
]
*/

為了完整起見,我們可以通過指定一個正確比較字符串的函數來獲得相同的結果。請注意,我們不必專門返回 -1;任何負值都可以。返回 1 時也是如此,因為任何正值都可以。

const compareStrings = (a, b) => {
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
};

zodiac.sort(compareStrings); // same result as above

正如我們在之前的文章中所描述的,我們應該注意到我們正在以“無點風格”工作。

這種排序很容易。降序呢?

以相反的順序對字符串進行排序

我們必須反轉標準比較以將數組排序為降序。讓我們從三個簡單的解決方案開始:

const reverseCompareStrings1 = (a, b) => {
  if (a < b) return 1;
  if (a > b) return -1;
  return 0;
};

const reverseCompareStrings2 = (a, b) => compareStrings(b, a); // Tricky!

const reverseCompareStrings3 = (a, b) => -compareStrings(a, b);

現在,我們通過使用任何反向比較函數將數組按降序排序。

zodiac.sort(reverseCompareStrings1); // or any of the other two instead
/*
[
 "Virgo", "Taurus", "Scorpio", "Sagittarius", 
 "Pisces", "Libra", "Leo", "Gemini", 
 "Capricorn", "Cancer", "Aries", "Aquarius"
]
*/

第一個函數很簡單,第二個有點棘手,但第三個是最有趣的:它為我們指出了另一種函數式編程風格的解決方案。對於我們可能想要實現的任何排序,從升序變為降序的關鍵是反轉比較符號。我們可以使用高階函數來處理這個問題,如本系列的前一篇文章所示。因此,我們可以執行以下操作:

const reverse = (fn) => (...args) => -fn(...args);

zodiac.sort(reverse(compareStrings)); // same result as above

從現在開始,通過使用我們的reverse(...)函數,我們可以非常簡單地將任何升序排序變為降序排序!

不考慮大小寫對字符串進行排序

讓我們考慮一種不同的情況——在不考慮大小寫差異的情況下對字符串進行排序呢?解決方案是比較字符串,但先將它們大寫。

const letItBe = ["When", "I", "find", "MYSELF", "in", "tiMes", "OF", "TRoubLE"];

letItBe.sort(compareStrings); // uppercase first, lowercase last
/*
["I", "MYSELF", "OF", "TRoubLE", "When", "find", "in", "tiMes"]
*/

const compareWithoutCase = (a, b) =>
  compareStrings(a.toUpperCase(), b.toUpperCase());

letItBe.sort(compareWithoutCase); // case ignored
/*
["find", "I", "in", "MYSELF", "OF", "tiMes", "TRoubLE", "When"]
*/

這是可行的——但我們將在下一節中看到更通用的解決方案。

對帶有外來字符的字符串進行排序

如果您嘗試對外語單詞進行排序會發生什麼?我將從我的Mastering JavaScript Functional Programming一書中舉一個例子。假設你想對一些西班牙語單詞(“palabras”)進行排序——會發生什麼?

const palabras = ["ñandú", "oasis", "mano", "natural", "mítico", "musical"];

palabras.sort(); // wrong result!
/*
"mano", "musical", "mítico", "natural", "oasis", "ñandú"
*/

在西班牙語中,“Ñ”位於“M”和“O”之間,因此“ñandú”被錯放了。類似地,“mítico”應該在“musical”之前(因為“i”在“u”之前)但這裡不是。解決這個問題的.localeCompare()方法是識別不同的語言。我們不會在這裡詳細介紹,但西班牙語排序問題很容易解決:

const spanishCompare = (a, b) => a.localeCompare(b, "es");

palabras.sort(spanishCompare); // right result
/*
"mano", "mítico", "musical", "natural", "ñandú", "oasis"
*/

我補充說它應該使用西班牙語(“es”)選項,因此現在根據該語言的規則進行比較。該.localeCompare()方法還接受更多選項,因此您可以指定大寫和小寫是單獨排序還是一起排序,是否應考慮或忽略重音符號和其他變音符號等。

排序數字和日期

對數字和日期進行排序並不復雜,但您必須考慮幾件事情。

排序數字

首先,我想指出,“合理”的數字排序方式是行不通的。

const numbers = [88, 1111, 444, 2];

numbers.sort(); // wrong result!
/*
[1111, 2, 444, 88]
 */

為什麼是這個結果?.sort(...)正如我們之前所說,該方法默認通過比較字符串進行排序。所以,當它與 比較881111,它實際上是在比較"88""1111"——第二個字符串在第一個之前!

指定比較函數對於按升序對字符串以外的任何內容進行排序是強制性的。對於數字,這個函數很容易編寫,因為如果我們有數字ab,那麼a-b如果是負數,如果是a<b正數,如果是a>ba===b,這正是我們所需要的!

const compareNumbers = (a, b) => a - b;

numbers.sort(compareNumbers); // right sort!
/*
[2, 88, 444, 1111]
 */

對於降序排序,我們只使用我們的reverse(...)函數。

numbers.sort(reverse(compareNumbers));
/*
[1111, 444, 88, 2]
 */

排序日期

排序日期呢?由於轉換為字符串慘敗,標準方式(意思是不提供排序功能)將不起作用。例如,我選擇了幾個與二戰相關的日期,但標準排序失敗。(如果日期對您來說很奇怪,請記住一月的月份編號從 0 開始,因此第一個日期是 1944 年 6 月 6 日,諾曼底登陸在霸王行動中。)排序時,比較從日期名稱開始,所以排序數組以 1943 年的日期開始,以 1942 年的日期結束;壞的!

const dates = [
  new Date(1944, 5, 6),  // Op. Overlord
  new Date(1940, 7, 10), // Battle of Britain
  new Date(1941, 11, 7), // Pearl Harbor
  new Date(1942, 5, 4),  // Battle of Midway
  new Date(1942, 7, 26), // Battle of Stalingrad
  new Date(1942, 10, 8), // Op. Torch
  new Date(1943, 6, 5),  // Battle of Kursk
  new Date(1941, 5, 22), // Op. Barbarossa
  new Date(1944, 11, 16) // Battle of the Bulge
];

dates.sort();
/*
[
Mon Jul 05 1943,
Sat Aug 10 1940,
Sat Dec 16 1944,
Sun Dec 07 1941,
Sun Jun 22 1941,
Sun Nov 08 1942,
Thu Jun 04 1942,
Tue Jun 06 1944,
Wed Aug 26 1942
]
*/

解決此問題的最簡單方法是使用.getTime()函數將日期轉換為數字。此函數將日期轉換為數字(如果您想知道,則為自 1970 年 1 月 1 日以來的毫秒數),但重要的是您可以直接比較這些數字。我們可以通過使用我們之前的compareNumbers(...)函數或直接通過減法來做到這一點。

const compareDates1 = (a, b) => compareNumbers(a.getTime(), b.getTime());

const compareDates2 = (a, b) => a.getTime() - b.getTime();

dates.sort(compareDates1); // or use compareDates2 instead
/*
[
Sat Aug 10 1940,
Sun Jun 22 1941,
Sun Dec 07 1941,
Thu Jun 04 1942,
Wed Aug 26 1942,
Sun Nov 08 1942,
Mon Jul 05 1943,
Tue Jun 06 1944,
Sat Dec 16 1944
]
*/

日期排序正確;一切都好。

排序布爾值

你能對布爾值進行排序嗎?是的,當然,雖然它不是很有趣,因為你只有兩個值可以使用!事實上,布爾值排序是“開箱即用”的,因為當 JavaScript 將布爾值轉換為字符串時,你會得到"false"and "true", and "false" < "true",所以一切都很好!

const flags = [true, false, true, false, true, false, false];
flags.sort();
/*
[false, false, false, false, true, true, true]
 */

我們也可以利用類型轉換,因為false它被轉換為 0,然後又true被轉換為 1。寫入+a將布爾值a轉換為數字,因此我們可以執行以下操作。

const compareBooleans = (a, b) => compareNumbers(+a, +b);

flags.sort(compareBooleans); // same result as above

我們現在完成了對簡單數組的排序;讓我們轉向由具有許多屬性和更複雜的排序要求的對象組成的排序數組。

排序對象

用單個值對數組進行排序很簡單,我們已經看到了所有情況的示例。必須對一組對象進行排序,每個對像都有幾個屬性,這種情況更為常見。幸運的是,我們可以使用已經編寫的函數以及一些額外的工作。

我們可以按一個或多個屬性對對象列表進行排序;讓我們做第二個,更一般的情況也包括第一個。假設我們有一個帶有group(數字)、subgroup(字符串)、total(數字)和額外other數據的對象。

const data = [
  { group: 2, subgroup: "B", total: 111, other: "alpha" },
  { group: 2, subgroup: "A", total: 444, other: "bravo" },
  { group: 1, subgroup: "A", total: 333, other: "charlie" },
  { group: 1, subgroup: "B", total: 222, other: "delta" },
  { group: 1, subgroup: "A", total: 555, other: "echo" },
  { group: 1, subgroup: "C", total: 777, other: "foxtrot" },
  { group: 1, subgroup: "A", total: 999, other: "golf" },
  { group: 2, subgroup: "B", total: 333, other: "hotel" },
  { group: 1, subgroup: "B", total: 666, other: "india" },
  { group: 2, subgroup: "A", total: 555, other: "joliet" }
];

我們要按組升序排序,在組內按子組升序排序,在子組內按總降序排序;我們該怎麼做?解決方案很簡單。給定兩個對象,如果group字段不匹配,我們已經知道哪個先出現;只是比較group字段。如果group字段匹配,但subgroup字段不匹配,我們也知道哪個在先;比較subgroup字段。如果subgroup字段也匹配,則比較取決於(反向)比較total字段。我們可以直接編碼。

const compareData = (a, b) => {
  if (a.group !== b.group) {
    return compareNumbers(a.group, b.group);
  } else if (a.subgroup !== b.subgroup) {
    return compareStrings(a.subgroup, b.subgroup);
  } else {
    return reverse(compareNumbers)(a.total, b.total);
  }
};

data.sort(compareData);

這非常有效——按幾個字段排序只是一個一個使用比較函數的問題。

[{group:1, subgroup:"A", total:999, other:"golf"},
 {group:1, subgroup:"A", total:555, other:"echo"},
 {group:1, subgroup:"A", total:333, other:"charlie"},
 {group:1, subgroup:"B", total:666, other:"india"},
 {group:1, subgroup:"B", total:222, other:"delta"},
 {group:1, subgroup:"C", total:777, other:"foxtrot"},
 {group:2, subgroup:"A", total:555, other:"joliet"},
 {group:2, subgroup:"A", total:444, other:"bravo"},
 {group:2, subgroup:"B", total:333, other:"hotel"},
 {group:2, subgroup:"B", total:111, other:"alpha"}]

排序——功能上?

我們現在已經討論了幾個排序的例子——但還有一個小細節:這種工作方式不是很實用!為什麼?因為該.sort()方法修改了它的輸入數組,這顯然是一個副作用。在真正的函數式風格中,排序應該返回一個新數組。(我們在不可變對像中討論了副作用和增變方法以提高狀態的安全性。)我們在那裡看到了一個解決方案,我們可以應用它來獲得更好的排序。如果我們想生成一個新數組,我們使用擴展運算符來生成一個副本,這就是我們的排序:

const newData = [...data].sort(compareData);

這個微小的變化會產生一個新的數組 ,newData保持原來的不變;輕鬆獲勝!

如果您願意,您也可以修改Array.prototype以添加新方法,但通常不建議這樣做……無論如何,如果您想這樣做,這將起作用:

Array.prototype.cleanSort = function (fn) {
  return [...this].sort(fn);
};

const newData = data.cleanSort(compareData);

這將起作用並生成一個新數組,而原始數組保持不變。但是,正如我所說,修改 JavaScript 對象的原型並不是一個很好的做法,而且可能會導致問題。被警告!

結論

在本文中,我們介紹了許多.sort()不同類型數據的使用示例,展示瞭如何使用這種方法來發揮我們的優勢。使用這些食譜,您應該能夠對任何您想要的東西進行分類;試試看!

鏈接:https ://blog.openreplay.com/forever-functional-sorting-recipes-for-javascript

#javascript

What is GEEK

Buddha Community

深入了解 JavaScript 的排序方法

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here https://bit.ly/31eZyDZ

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips

Ajay Kapoor

1626321063

JS Development Company India | JavaScript Development Services

PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.

With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.

Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.

Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.

#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company

Nat  Grady

Nat Grady

1670062320

How to Use Zapier with MongoDB

I’m a huge fan of automation when the scenario allows for it. Maybe you need to keep track of guest information when they RSVP to your event, or maybe you need to monitor and react to feeds of data. These are two of many possible scenarios where you probably wouldn’t want to do things manually.

There are quite a few tools that are designed to automate your life. Some of the popular tools include IFTTT, Zapier, and Automate. The idea behind these services is that given a trigger, you can do a series of events.

In this tutorial, we’re going to see how to collect Twitter data with Zapier, store it in MongoDB using a Realm webhook function, and then run aggregations on it using the MongoDB query language (MQL).

The Requirements

There are a few requirements that must be met prior to starting this tutorial:

  • A paid tier of Zapier with access to premium automations
  • A properly configured MongoDB Atlas cluster
  • A Twitter account

There is a Zapier free tier, but because we plan to use webhooks, which are premium in Zapier, a paid account is necessary. To consume data from Twitter in Zapier, a Twitter account is necessary, even if we plan to consume data that isn’t related to our account. This data will be stored in MongoDB, so a cluster with properly configured IP access and user permissions is required.

You can get started with MongoDB Atlas by launching a free M0 cluster, no credit card required.

While not necessary to create a database and collection prior to use, we’ll be using a zapier database and a tweets collection throughout the scope of this tutorial.

Understanding the Twitter Data Model Within Zapier

Since the plan is to store tweets from Twitter within MongoDB and then create queries to make sense of it, we should probably get an understanding of the data prior to trying to work with it.

We’ll be using the “Search Mention” functionality within Zapier for Twitter. Essentially, it allows us to provide a Twitter query and trigger an automation when the data is found. More on that soon.

As a result, we’ll end up with the following raw data:

{
    "created_at": "Tue Feb 02 20:31:58 +0000 2021",
    "id": "1356701917603238000",
    "id_str": "1356701917603237888",
    "full_text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript",
    "truncated": false,
    "display_text_range": [0, 188],
    "metadata": {
        "iso_language_code": "en",
        "result_type": "recent"
    },
    "source": "<a href='https://about.twitter.com/products/tweetdeck' rel='nofollow'>TweetDeck</a>",
    "in_reply_to_status_id": null,
    "in_reply_to_status_id_str": null,
    "in_reply_to_user_id": null,
    "in_reply_to_user_id_str": null,
    "in_reply_to_screen_name": null,
    "user": {
        "id": "227546834",
        "id_str": "227546834",
        "name": "Nic Raboy",
        "screen_name": "nraboy",
        "location": "Tracy, CA",
        "description": "Advocate of modern web and mobile development technologies. I write tutorials and speak at events to make app development easier to understand. I work @MongoDB.",
        "url": "https://t.co/mRqzaKrmvm",
        "entities": {
            "url": {
                "urls": [
                    {
                        "url": "https://t.co/mRqzaKrmvm",
                        "expanded_url": "https://www.thepolyglotdeveloper.com",
                        "display_url": "thepolyglotdeveloper.com",
                        "indices": [0, 23]
                    }
                ]
            },
            "description": {
                "urls": ""
            }
        },
        "protected": false,
        "followers_count": 4599,
        "friends_count": 551,
        "listed_count": 265,
        "created_at": "Fri Dec 17 03:33:03 +0000 2010",
        "favourites_count": 4550,
        "verified": false
    },
    "lang": "en",
    "url": "https://twitter.com/227546834/status/1356701917603237888",
    "text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}

The data we have access to is probably more than we need. However, it really depends on what you’re interested in. For this example, we’ll be storing the following within MongoDB:

{
    "created_at": "Tue Feb 02 20:31:58 +0000 2021",
    "user": {
        "screen_name": "nraboy",
        "location": "Tracy, CA",
        "followers_count": 4599,
        "friends_count": 551
    },
    "text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}

Without getting too far ahead of ourselves, our analysis will be based off the followers_count and the location of the user. We want to be able to make sense of where our users are and give priority to users that meet a certain followers threshold.

Developing a Webhook Function for Storing Tweet Information with MongoDB Realm and JavaScript

Before we start connecting Zapier and MongoDB, we need to develop the middleware that will be responsible for receiving tweet data from Zapier.

Remember, you’ll need to have a properly configured MongoDB Atlas cluster.

We need to create a Realm application. Within the MongoDB Atlas dashboard, click the Realm tab.

MongoDB Realm Applications

For simplicity, we’re going to want to create a new application. Click the Create a New App button and proceed to fill in the information about your application.

From the Realm Dashboard, click the 3rd Party Services tab.

Realm Dashboard 3rd Party Services

We’re going to want to create an HTTP service. The name doesn’t matter, but it might make sense to name it Twitter based on what we’re planning to do.

Because we plan to work with tweet data, it makes sense to call our webhook function tweet, but the name doesn’t truly matter.

Realm Tweet Webhook

With the exception of the HTTP Method, the defaults are fine for this webhook. We want the method to be POST because we plan to create data with this particular webhook function. Make note of the Webhook URL because it will be used when we connect Zapier.

The next step is to open the Function Editor so we can add some logic behind this function. Add the following JavaScript code:

exports = function (payload, response) {

    const tweet = EJSON.parse(payload.body.text());

    const collection = context.services.get("mongodb-atlas").db("zapier").collection("tweets");

    return collection.insertOne(tweet);

};

In the above code, we are taking the request payload, getting a handle to the tweets collection within the zapier database, and then doing an insert operation to store the data in the payload.

There are a few things to note in the above code:

  1. We are not validating the data being sent in the request payload. In a realistic scenario, you’d probably want some kind of validation logic in place to be sure about what you’re storing.
  2. We are not authenticating the user sending the data. In this example, we’re trusting that only Zapier knows about our URL.
  3. We aren’t doing any error handling.

When we call our function, a new document should be created within MongoDB.

By default, the function will not deploy when saving. After saving, make sure to review and deploy the changes through the notification at the top of the browser window.

Creating a “Zap” in Zapier to Connect Twitter to MongoDB

So, we know the data we’ll be working with and we have a MongoDB Realm webhook function that is ready for receiving data. Now, we need to bring everything together with Zapier.

For clarity, new Twitter matches will be our trigger in Zapier, and the webhook function will be our event.

Within Zapier, choose to create a new “Zap,” which is an automation. The trigger needs to be a Search Mention in Twitter, which means that when a new Tweet is detected using a search query, our events happen.

Zapier Twitter Search Mention

For this example, we’re going to use the following Twitter search query:

url:developer.mongodb.com -filter:retweets filter:safe lang:en -from:mongodb -from:realm

The above query says that we are looking for tweets that include a URL to developer.mongodb.com. The URL doesn’t need to match exactly as long as the domain matches. The query also says that we aren’t interested in retweets. We only want original tweets, they have to be in English, and they have to be detected as safe for work.

In addition to the mentioned search criteria, we are also excluding tweets that originate from one of the MongoDB accounts.

In theory, the above search query could be used to see what people are saying about the MongoDB Developer Hub.

With the trigger in place, we need to identify the next stage of the automation pipeline. The next stage is taking the data from the trigger and sending it to our Realm webhook function.

Zapier to Realm Webhook

As the event, make sure to choose Webhooks by Zapier and specify a POST request. From here, you’ll be prompted to enter your Realm webhook URL and the method, which should be POST. Realm is expecting the payload to be JSON, so it is important to select JSON within Zapier.

We have the option to choose which data from the previous automation stage to pass to our webhook. Select the fields you’re interested in and save your automation.

The data I chose to send looks like this:

{
    "created_at": "Tue Feb 02 20:31:58 +0000 2021",
    "username": "nraboy",
    "location": "Tracy, CA",
    "follower_count": "4599",
    "following_count": "551",
    "message": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}

The fields do not match the original fields brought in by Twitter. It is because I chose to map them to what made sense for me.

When deploying the Zap, anytime a tweet is found that matches our query, it will be saved into our MongoDB cluster.

Analyzing the Twitter Data in MongoDB with an Aggregation Pipeline

With tweet data populating in MongoDB, it’s time to start querying it to make sense of it. In this fictional example, we want to know what people are saying about our Developer Hub and how popular these individuals are.

To do this, we’re going to want to make use of an aggregation pipeline within MongoDB.

Take the following, for example:

[
    {
        "$addFields": {
            "follower_count": {
                "$toInt": "$follower_count"
            },
            "following_count": {
                "$toInt": "$following_count"
            }
        }
    }, {
        "$match": {
            "follower_count": {
                "$gt": 1000
            }
        }
    }, {
        "$group": {
            "_id": {
                "location": "$location"
            },
            "location": {
                "$sum": 1
            }
        }
    }
]

There are three stages in the above aggregation pipeline.

We want to understand the follower data for the individual who made the tweet, but that data comes into MongoDB as a string rather than an integer. The first stage of the pipeline takes the follower_count and following_count fields and converts them from string to integer. In reality, we are using $addFields to create new fields, but because they have the same name as existing fields, the existing fields are replaced.

The next stage is where we want to identify people with more than 1,000 followers as a person of interest. While people with fewer followers might be saying great things, in this example, we don’t care.

After we’ve filtered out people by their follower count, we do a group based on their location. It might be valuable for us to know where in the world people are talking about MongoDB. We might want to know where our target audience exists.

The aggregation pipeline we chose to use can be executed with any of the MongoDB drivers, through the MongoDB Atlas dashboard, or through the CLI.

Conclusion

You just saw how to use Zapier with MongoDB to automate certain tasks and store the results as documents within the NoSQL database. In this example, we chose to store Twitter data that matched certain criteria, later to be analyzed with an aggregation pipeline. The automations and analysis options that you can do are quite limitless.

If you enjoyed this tutorial and want to get engaged with more content and like-minded developers, check out the MongoDB Community.

This content first appeared on MongoDB.

Original article source at: https://www.thepolyglotdeveloper.com/

#mongodb #zapier