Locate unique values for a specific field in MongoDB documents using Mongoose

Imagine a scenario where there is a Schema named MyDoc with a field called key. Here are the sample documents:

[
  {
    "key": 1
  },
  {
    "key": 2
  },
  {
    "key": 2
  },
  {
    "key": 3
  },
  {
    "key": 3
  },  
  {
    "key": 3
  },
  {
    "key": 4
  }

]

Using mongoose, the goal is to retrieve documents that have a unique value in the key field. In other words, fetch all documents where no other document shares the same key value.

In the aforementioned example data, there are multiple documents with keys 2 and 3, while only one document each has keys 1 and 4. Therefore, the desired outcome would be to return only the documents with keys 1 and 4.

Answer №1

To find unique values, one option is to use aggregation group:

db.collection.aggregate([
{
 $group: {
  _id: "$identifier",
  count: {
    $sum: 1
  }
  }
 },
 {
  $match: {
  count: {
    $eq: 1
  }
 }
 },
 {
 $project: {
  identifier: "$_id",
  _id: 0
 }
}
])

Explanation of stages:

  1. Group by the unique identifier to count the duplicates
  2. Filter only those with no duplicates
  3. Show only the necessary identifiers in the output

Mongo Playground Link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulating DropDownList Attributes in ASP.NET using JavaScript

I am facing an issue with populating a Dropdownlist control on my ASCX page. <asp:DropDownList ID="demoddl" runat="server" onchange="apply(this.options[this.selectedIndex].value,event)" onclick="borderColorChange(this.id, 'Click')" onblur="bo ...

Showing specific XML data from a node when a button is clicked in an HTML document

<script> $(document).ready(function(){ $.ajax({ type: "GET", url: "data.xml", dataType: "xml", success: function(xmlData) { $("POS", xmlData).each(function(){ var sr = $(this).find(&apos ...

The sorting icon cannot be substituted with jQuery, AJAX, or PHP

Currently, I am working on implementing "sort tables" using ajax, jquery, and PHP. The sorting function is functioning correctly; however, I need to show/hide the "sorting images". At the moment, only one-sided (descending) sorting is operational because I ...

How to smoothly fade out content when hovering over a menu item in HTML<li> tags

Hi there, I have encountered a problem and could really use your assistance. I am attempting to create a menu that displays content when you hover over an li tag. The first content should always be visible when hovering over the first li option or if no l ...

Should locator names be utilized in templates for the purpose of simplifying E2E tests?

When conducting deep nested tests, I often struggle to locate the items I need. Would it be unwise to use something like <h1 name="test-main-title">About Us</h1> and simply utilize element(by.name('test-main-title'));? Afterwards ...

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

Querying and updating MongoDB's ObjectIDs

Hi everyone, I'm working on a MongoDB query to update a document by incrementing a specific field by 1. However, I'm encountering an issue with matching the document's key with the data sent from the frontend. This is how my database looks: ...

How is the purpose of nesting functions within functions achieved in nodejs?

Take a look at this example: var tools1 = require('../tools/tools1'); var test_func = function(arg1, arg2, arg3) { var local_var_1 = "lc1"; var local_var_2 = "lc2"; return function(data) { var result = tools1.doSth(local_va ...

The functionality of res.status().send() appears to be malfunctioning when used within a Promise

I am currently working on a code that involves checking authorization from two different API calls within a promise.all method. If any of the authorizations fail, I want to throw the respective res.send method as an error. However, I keep encountering an " ...

Ensure that the bootstrap-datepicker field is validated when it is changed

My goal is to validate the order_datePicker input field when it is filled by using bootstrap-datepicker. Although I have come across some answers on stackoverflow, I am unable to make it work on my own. I have been successful with other input fields using: ...

No data retrieved from MongoDB due to lack of results

Having an issue with fetching data from MongoDB using Node.js. Even though I believe the connection to the database is established and collections are accessible, I only receive an empty response. Below is my Server.js file: // set up =================== ...

Exploring MongoDB: Effective Techniques for Filtering Nested Arrays of Objects

Here are two examples from my collection { '_id': ObjectId('6287443338ed135a9e0b1b9d'), 'data': [{'pChange': 166.9602348545503, 'strikePrice': 34000}, {'pChange': -55.820553402827045, & ...

Invoke an Ajax function to trigger another Ajax function once complete

var App = { actionRequest: function (url,data,callback){ var that = this; $('#menu').panel('close'); $.mobile.loading('show'); $.when( $.ajax({ method: 'POST', url: ur ...

Identifying the Source of a Page Redirection in Javascript: A Step-by-Step Guide

After downloading a free template from the internet, I noticed that there was a link back to the website in the footer. Upon attempting to remove this link, my page started redirecting to the homepage URL of the original website. How can I pinpoint which ...

Using JavaScript to control the scrolling behavior on a Bootstrap modal

Looking for a solution regarding my Bootstrap modal situation. I have a modal with a scroll bar, and what I want is that each time a user clicks on a button in the modal body, a function should be executed to move to the next step of a wizard within the mo ...

Struggling to generate a div using my JS/jQuery code

Currently working on a post-it web application to improve my skills in JavaScript and jQuery. I've encountered a few errors that have me stumped. Although I'm new to StackOverflow, I often use it as a helpful resource. You can find the code here ...

Second attempt to fire DataTable select function fails

Currently, I have 2 tables displayed in my view. The first table, table1, is where I select a row and the data from that selection is returned in table2. The issue I am facing is that when I try to select the second row in table1, it does not send an ajax ...

jquery sliding down effect - glide gracefully with the slide down

I am interested in creating an effect on my page that is similar to HostGator's live chat feature. I have searched for solutions here and found something close to what I want to achieve. However, the issue is that the div starts at a height of 1px and ...

Possible issue with accurate indexing causing caption error with API images in React

Continuing from: Implementing a lightbox feature in react-multi-carousel for my ReactJS app My application utilizes react-images for the lightbox functionality and react-carousel-images for the carousel. The API provides a title and image data. The issue ...

Is it possible to use Vuejs v-model for a complete form instead of individual inputs?

Note: This solution is applicable for Vue 2.X I am currently working on a unique Vue.js component that has the ability to generate "custom" forms. This component essentially functions as a standalone form with multiple input fields. Users have the option ...