Encountering a problem: "The '$acknowledged' field name is invalid as an operator in the aggregation query."

I'm attempting to retrieve the most recent messages between User A and any other user.

Unfortunately, I am encountering an error message that states:

The field name '$acknowledged' cannot be an operator name

I am unsure of what mistake I might be making. Here is a link to the Mongo playground.

The desired outcome is to display the latest message exchanged between a user with the ID 5a934e000102030405000001 and another user.

[
    {
      "from": ObjectId("5a934e000102030405000002"),
      "to": ObjectId("5a934e000102030405000001"),
      "acknowledged": true,
      date: "2020-04-17T18:26:34.353+00:00"
    },
    {
      "from": ObjectId("5a934e000102030405000001"),
      "to": ObjectId("5a934e000102030405000003"),
      "acknowledged": false,
      date: "2020-04-17T18:26:31.353+00:00"
    },
    {
      "from": ObjectId("5a934e000102030405000004"),
      "to": ObjectId("5a934e000102030405000001"),
      "acknowledged": false,
      date: "2020-04-17T18:26:29.353+00:00"
    },
]

Answer №1

There was a small mistake in this section:

$acknowledged: {                     acknowledged: {
   $first: "$acknowledged",   -->      $first: "$acknowledged"
                                     }
},
                              also,
then: "$responseTo",          -->    then: "$to",

db.Message.aggregate([
  {
    $match: {
      $or: [
        {
          from: {
            $in: [
              ObjectId("5a934e000102030405000001")
            ]
          }
        },
        {
          to: {
            $in: [
              ObjectId("5a934e000102030405000001")
            ]
          }
        }
      ]
    }
  },
  {
    $sort: {
      date: -1
    }
  },      
  {
    $group: {
      _id: {
        userConcerned: {
          $cond: [
            {
              $in: [
                "$to",
                [
                  ObjectId("5a934e000102030405000001")
                ]
              ]
            },
            "$to",
            "$from"
          ]
        },
        interlocutor: {
          $cond: [
            {
              $in: [
                "$to",
                [
                  ObjectId("5a934e000102030405000001")
                ]
              ]
            },
            "$from",
            "$to"
          ]
        }
      },
      id: {
        $first: "$_id"
      },
      from: {
        $first: "$from"
      },
      acknowledged: {
        $first: "$acknowledged"
      },
      to: {
        $first: "$to"
      },
      date: {
        $first: "$date"
      }
    }
  },
  {
    $lookup: {
      from: "User",
      localField: "to",
      foreignField: "_id",
      as: "to"
    }
  },
  {
    $unwind: "$to"
  },
  {
    $lookup: {
      from: "User",
      localField: "from",
      foreignField: "_id",
      as: "from"
    }
  },
  {
    $unwind: "$from"
  },
  {
    $project: {
      _id: 0,
      date: 1,
      acknowledged: 1,
      from: "$from._id",
      to: "$to._id"
    }
  }
])

Check it out on MongoPlayground

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

Leveraging external objects in Vue.js computed functions

Can Vue's computed property be used with an external object? Let's consider the following code example to illustrate the idea: <!-- Vue file --> <template> <div>{{data.auth}}</div> </template> <script> i ...

Create images from HTML pages with the help of Javascript

Hello there, UPDATE: I am looking to achieve this without relying on any third-party software. My application is a SAP product and installing additional software on every customer's system is not feasible. The situation is as follows:   ...

JavaScriptCore now includes the loading of AMD modules

I am trying to incorporate a JavaScript module into JavascriptCore on iOS. To achieve this, I am fetching the file's text through a standard HTTP request on the iOS platform. Once I have obtained the entire string, I plan to parse it into the JSconte ...

Adjust the size of the image as needed in order to fit within a container of fixed

Is there a clever way to use CSS and/or JavaScript/jQuery to adjust the size of images only when necessary for them to fit within a fixed-height container alongside the remaining content? Upon reviewing the images in the 'new this week' and &apos ...

Change the URL structure from ex.com/forum?id=1 to ex.com/#/forum?id=1 in AngularJS

Hey there! I'm in the process of creating a Forum using AngularJS and need some guidance. First things first! I've successfully established a connection to my database with: <?php session_start(); $db = new mysqli("localhost","root",""," ...

What could be causing my node server's REST endpoints to not function properly?

Here is a snippet of my index.js file: var http = require('http'); var express = require('express'); var path = require('path'); var bodyParser = require('body-parser') var app = express(); var currentVideo = &apos ...

Activating the Play button to start streaming a link

Recently delved into the world of Ionic 4 and Angular, so definitely a beginner :) Purchased a UI Template from code canyon but didn't realize I needed to code the music player part. Been trying to get a music stream playing but no luck. Came across ...

Creating a dynamic dropdown menu based on a class value using JavaScript in PHP

There are two dropdown menus on my webpage that display information from my SQL table. The first dropdown contains different "Colors," and the second dropdown contains members associated with each color group. Each member is categorized into different optg ...

What is the best way to highlight excess characters in Kendo UI Editor by setting the selectedRange, similar to Twitter's feature

Can anyone provide guidance on wrapping parts of the nodes in a Kendo UI Editor with a span when they exceed the character limit? I'm looking to replicate the feature in Twitter where excess characters are shown in red. Is there a way to adjust the s ...

Any ideas on how to format a date for jQuery Datepicker?

Currently, I have implemented two different datepickers on my website, but I am interested in switching to jQuery's Datepicker for a more unified solution. Here is the current format that I am sending to our backend API: However, I would prefer to i ...

Issue encountered in React: Unable to access object value within ComponentDidUpdate method

I'm struggling to retrieve the value from an object key. componentDidUpdate(prevProps) { if (prevProps !== this.props) { console.log("component did update in top menu", this.props.topmenudata[0]) this.setState({ ...

Using `require(variable)` is not functional in next-js environment

I'm attempting to display an image using the next-optimised-images module. When I try to include images like this: <img src={require(c.logo)} alt={c.title} /> I encounter the following error: https://i.stack.imgur.com/Jtqh9.png However, when ...

Generating various fields within a single row

I am in the process of creating a dynamic form that should generate two new fields in the same line when the user clicks on the plus icon. Currently, the code I have only creates a single field. I attempted to duplicate the code within the function, but i ...

Angular checkboxes not triggering ng-click event

Within my Angular application, there is a form that includes checkbox inputs: <div ng-repeat="partner in type.partners"> <label class="checkbox-inline"> <input type="checkbox" value="partner" ng-checked="report.participa ...

Using javascript, add text to the beginning of a form before it is submitted

I'm trying to modify a form so that "https://" is added to the beginning of the input when it's submitted, without actually showing it in the text box. Here's the script I have so far: <script> function formSubmit(){ var x ...

Step-by-step guide on entering text into a hidden field with Selenium WebDriver and Java

I am currently utilizing WebDriver in conjunction with Java for automated testing. I have come across a hidden input field within the following HTML code: <input type="hidden" value="" name="body" id=":6b"> My challenge lies in trying to input data ...

"Troubleshooting the issue with the jQuery function not being able to trigger a

When I press the enter key in an input field, I want to be able to select options from a searchable dropdown menu. However, this functionality is not working and the alert message I set up is also not functioning as expected. <div class="form-group m-f ...

Is there a way to modify the log() function to handle multiple arguments?

Recently, I've been utilizing this logger in node.js: // Found on stackoverflow: https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color function logC(text) { console.log('\x1b[36m%s\x1b[0m', text); ...

Retrieve the property by mapping the click event

I am looking for a way to retrieve the ID of a specific item when a link button inside a mapped list is clicked. How can I achieve this functionality? idFinder(){ console.log('ID:', item.id); } this.sampleData = this.state.data.map((item, ...

Vue caution: The reference to property or method "list" during render is not defined on the instance. Ensure that this property is reactive and properly declared

I'm currently exploring the characters from the Rick & Morty series app using vue.js, and I am still learning how to use vue.js. However, I encountered the following error and would appreciate help in resolving it: Error1: [Vue warn]: Property or me ...