Implement and remove changes in mongodb

My database sample looks like this:

db={
  "sample": [
    {
      current_book: "Aurthor",
      upcoming_book: [
        "Sigma",
        "Rocky"
      ]
    }
  ]
}

I am trying to update the current_book value to the first element of upcoming_book and remove that element from upcoming_book.

Desired Output:

[
  {
    "current_book": "Sigma",
    "upcoming_book": [
      "Rocky"
    ]
  }
]

I attempted the following:

db.sample.update({
  "upcoming_book.0": {
    $exists: true
  }
},
{
  "$set": {
    current_book: {
      $arrayElemAt: [
        "$upcoming_book",
        0
      ]
    }
  },
  "$pop": {
    "upcoming_book": -1
  }
})

However, it incorrectly updates the current_book value and removes the value from upcoming_book.

Output:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "current_book": {
      "$arrayElemAt": [
        "$upcoming_book",
        0
      ]
    },
    "upcoming_book": [
      "Rocky"
    ]
  }
]

I also attempted to use the aggregation pipeline:

db.sample.update({
  "upcoming_book.0": {
    $exists: true
  }
},
[
  {
    $set: {
      current_book: {
        $arrayElemAt: [
          "$upcoming_book",
          0
        ]
      }
    }
  },
  {
    "$pop": {
      "upcoming_book": -1
    }
  }
])

But this resulted in an error:

fail to run update: (Location40324) Unrecognized pipeline stage name: '$pop'.

https://mongoplayground.net/p/1j8DTlOHDV3

Answer №1

Are you interested in this solution?

[
  {
    "$set": {
      current_item: {
        $arrayElemAt: [
          "$upcoming_item",
          0
        ]
      },
      "upcoming_item": {
        $slice: [
          "$upcoming_item",
          -1
        ]
      }
    }
  }
]

See an example in the playground here results in:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "current_item": "Alpha",
    "upcoming_item": [
      "Beta"
    ]
  }
]

A more versatile solution with dynamic sizing might be:

[
  {
    "$set": {
      current_item: {
        $arrayElemAt: [
          "$upcoming_item",
          0
        ]
      },
      "upcoming_item": {
        $slice: [
          "$upcoming_item",
          {
            $subtract: [
              1,
              {
                $size: "$upcoming_item"
              }
            ]
          }
        ]
      }
    }
  }
]

Check out this playground example.

If you encounter the error message (

Unrecognized pipeline stage name: '$pop'
), I discuss a solution here.

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

Utilizing React hooks to dynamically toggle a class within a component

While similar questions have been raised previously, none seem to address my specific issue. Most references involve class components that do not align exactly with what I am attempting to achieve. My goal is to toggle two components on and off with a simp ...

Is there a simpler method for making multiple posts using an AJAX JS loop?

My form is quite extensive and uses AJAX to save. The JavaScript functions are stored in an external file and structured like this: function milestone09() { $.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#milestone09').serialize( ...

Send the user to a specified destination

Currently, I am working on creating a form that allows users to input a location and have the page redirect to that location after submission. However, I am facing difficulty in determining how to set the value for action="" when I do not know what the loc ...

A guide on transferring a Vue component to a custom local library

After successfully creating components using template syntax (*vue files), I decided to move common components to a library. The component from the library (common/src/component/VButton): <template> <button ... </button> </templat ...

Modifying website elements with JavaScript

Can someone assist me with getting a script to work on my website that will allow me to switch between four different sets of content using buttons labeled 1, 2, 3, and 4? I have tried using addClass and removeClass but cannot seem to get it right. Here i ...

The use of multiple Where clauses in a Firestore Firebase query is not functioning as expected when implemented in JavaScript code

https://i.stack.imgur.com/DdUGj.png db.collection('User_Info').where("User_Name", "==", "Sam").where("PASSWORD", "==", "c2FtMTIzQA==").get().then(snapshot => { if(snapshot.docs.length > 0 ){ debugger; alert("Login Successful."); ...

detecting key presses on documents using javascript

I'm having trouble capturing document-level key press events on a webpage. I've tried using the following code: $(document).bind('keydown', 'a', keyevent_cb); It works fine in IE, but it's not consistent in Firefox. I&a ...

Is the sudden disconnection from Chrome after a WebSocket handshake related to a domain mismatch or is it possibly a bug in Chrome?

I created my own WebSocket server using Python, but I encountered an issue where Chrome 4.0.249.78 dev (36714) always disconnects after the handshake process. Wanting to rule out any issues with my code, I tested it using the WebSocket server from , only t ...

Comparing react-intl and react-i18next for internationalizing ReactJS applications

I am in the process of developing a multilanguage application using ReactJS. This application will require a custom dictionary for various languages, as well as automatic formatting for date/time, numbers, and currency. After researching, I have come acro ...

Utilizing the power of jQuery's $.each method to dynamically generate HTML select options within an AJAX

I am working with a bootstrap modal that includes a form which requires data from the database. To retrieve this data, I am using PHP as shown below: public function get_view_for_inspection_report_belum_eor(){ $q = $this->inspection->get_view_fo ...

Issues with Mongoose connection in NextJS

I have been working on a small NextJS demo project where I utilize server actions to retrieve documents from MongoDB through Mongoose. However, I am encountering an error in my terminal that says: MongoNotConnectedError: Client must be connected before ru ...

Connect the dxSelectBox to the button click event

Currently, I am working with the DevExtreme MVVM architecture. In my specific situation, I am trying to bind a dxSelectBox (combo box) upon a button click event. Here is the HTML CODE snippet: <div data-bind="dxButton:{onClick:display,text:'Click ...

Error thrown when attempting to access properties of null values (Uncaught TypeError: Cannot read properties of undefined (reading 'map'))

import React, { useState, useEffect } from "react"; import { TaskLists } from "./TaskLists"; import { Daycard } from "./daycard"; import { getTasks, deleteTask } from "../api/task.api"; export function TaskManager() { const [tasks, setTasks] = useState( ...

I am encountering an issue with identifying a directory in Node.js

This is my HTML code <div id="done_work_1" class="logo-slide-track"> </div> <script>$.ajax({ url: "/static/home/done/", success: function (data) { $(data).find("a").attr("href&q ...

What steps should I take to establish routes in my node and express application that allow for authentication through a designated method?

Currently, I am following the backend set up tutorial from auth0, and I have a question regarding how to organize my routes in a separate file rather than in the app.js. In the tutorial, they demonstrate var authenticate = jwt({ secret: new Buffer(proc ...

Utilizing arrays dynamically to generate data for a bar chart display in JavaScript

I'm currently working on generating a bar stack graph using the chart.js JavaScript library. My JavaScript array contains the following data: 0: {labels: "01/01/2020 00:00:00", data: 7433, category: "A"} 1: {labels: "01/01/2020 00:00:00", data: 774, ...

The href attribute is not functioning correctly on Internet Explorer version 8

When dynamically generating HTML and appending the response to a DIV, here is the jQuery code: {% elif topic|length < 1 or topic.user_exhausted_attempts %} $('.questionHolder').hide(); var html = '<section class="span9">&a ...

What is the process for accessing data of signed-in users?

I currently have a mobile app developed using the MERN stack that utilizes passportjs for user authentication and login (linked to a mongodb database via axios). However, I am facing an issue where I cannot associate the data/log entered by the user with t ...

What sets apart an object within the scalajs scope from the exact same object within the js.global scope?

Attempting to create a basic example for rendering a cube using the THREEJS library. package three import org.scalajs.dom import scala.scalajs.js import scala.scalajs.js.Dynamic._ import scala.scalajs.js.annotation.JSName ... object ThreeExample { d ...

Restricting the number of lines within a paragraph in Angular 2

Is there a method to limit the number of lines in a <p> tag and add an ellipsis (...) at the end? Using character count for truncation doesn't work well as the width of the element varies according to device screen size. ...