Retrieve a value from a different collection in MongoDb

Is it possible to copy certain fields from one collection to another?

I am looking to copy the values of 'bar' to the 'foo' collection, excluding the 'type' field. Additionally, I want to add a new _id and an extra field (userId) to 'foo' using Node.js.

collection bar
{
    "_id" : ObjectId("77777777ffffff9999999999"),
    "type" : 0,
    "name" : "Default",
    "index" : 1,
    "layout" : "1",    
}


collection foo
{
    "_id" : NEW OBJECT ID,
//    "type" : 0, NOT INCLUDED IN THIS COLLECTION
    "userId" : ObjectId("77777777ffffff9999999911"),
    "name" : "Default",
    "index" : 1,
    "layout" : "1",    
}

I attempted using db.bar.copyTo("foo");, but it copied the entire collection instead.

Answer №1

One of the best options in this situation is to remove the unwanted field from your collection. You can achieve this by using the $unset operator:

db.collection.update({ },{ "$unset": { "fieldToRemove": 1 } },false,true)

This command will remove the specified field from all documents in your collection with just one statement.

Starting from version 2.6, you can also achieve this with the aggregate method:

db.collection.aggregate([
    { "$project": {
        "field1": 1,
        "field2": 1,
        "field3": 1
    }},
    { "$out": "newCollection" }
])

The new $out stage in aggregation sends the result to a new collection.

Answer №2

To transfer fields between collections, you can employ the following method:

 db.sourceCollection.find().forEach(function(item){

    db.targetCollection.update(
    {"_id" : ObjectId("53205a4a139485ab43e25a72")}, //specify update condition

    { $set:{fieldName:item.fieldName}
});

});

This script iterates through the data using the provided function. It loops through the source collection to extract the data, then updates or inserts it into the target collection document.

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

The Jquery confirmation dialogue does not seem to be functioning properly within the Content Place Holder

I've encountered an issue with a JQUERY Confirm dialogue where it works perfectly fine until I place it on a page that is within a masterpage. The confirm alert pops up for a split second and disappears. window.onload = function() { $("#ehi").cli ...

PHP is returning an empty response during an AJAX request

I am facing an issue with my AJAX request where I am trying to return a simple echo, but for some reason, it's not working this time. Even after stripping down the code to its bare essentials, the response is still blank. Javascript function getUs ...

javascript implementing number formatting during keyup event

When I try to format a number in an input field on the keyup event, I receive a warning in my browser console that says "The specified value "5,545" cannot be parsed, or is out of range." The value in the input field also gets cleared. How can I solve this ...

What is the best way to eliminate base tags from jQuery mobile scripts?

In jQuery Mobile, how can I remove the base href tags from the page and disable base href? Code Snippet: // Function to test for dynamic-updating base tag support function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + l ...

Preserve content from a hyperlink using JavaScript

How can I store a value to the cache using JavaScript when clicking on an anchor link? The code below sets up the dynamic content: <a align="left" href="projectoverview.html">Test Manager</a> I want to save the text "Test Manager" to the cach ...

How can we stop the page from scrolling after a click?

Upon clicking the link labeled Click Me, the page automatically scrolls back to the top. This behavior is not desired. How can I correct this issue? For example, here is a link to a relevant resource: http://jsfiddle.net/Y6Y3Z/ Regarding the scroll-bar: ...

Moving a DOM element within AngularJS to a new location

I have created an angular directive that functions like a carousel. To keep the dom element count low, I delete elements from the dom and then re-insert them using angular.element to select, remove, and insert items as shown below: app.directive('myD ...

Troubleshooting data binding problems when using an Array of Objects in MatTableDataSource within Angular

I am encountering an issue when trying to bind an array of objects data to a MatTableDataSource; the table displays empty results. I suspect there is a minor problem with data binding in my code snippet below. endPointsDataSource; endPointsLength; endP ...

Incorporate Aria Label into a Website Link

Currently working on enhancing website accessibility. I have identified a close menu button that lacks an Aria Label, and my goal is to rectify this using JavaScript. Although I am utilizing the script below to target the specific ID and add the attribute ...

The error message "window is not defined" is commonly encountered in Next

Having some trouble with using apexcharts in a next.js application, as it's giving me an error saying 'window is not defined'. If anyone has any insights or solutions, I would greatly appreciate the help. Any ideas on what could be causing ...

Performing three consecutive Ajax requests in a Rails application

Recently, I developed a custom admin system for a local gym to manage payments, attendance, mailing, sales, and more. While everything is functioning smoothly, there seems to be an issue with the attendance feature. Occasionally, when taking attendance, an ...

Ways to expedite the process of retrieving data for a JavaScript array

Looking to acquire the creation date of 20000 files and save it in an array. The total time taken is 35 minutes, which seems quite lengthy. (Image Processing Time) Is there a method to generate the array with a quicker processing time? Are there any i ...

Change a CSV string into a JSON array and assign it to a variable

I am working with JSON data that looks like this: [ { "Title": "PAGE A", "Users": "USRA" }, { "Title": "PAGE B", "Users": "USRA,USRB" } ] What is the most efficient method to convert the fields containing " ...

The dropdown menu button stubbornly remains open and refuses to close

Having an issue with a dropdown menu button where it should open when clicked on the icon and close when clicking off the icon or on the icon again, but instead, it remains open. Here is a screenshot for reference: https://i.stack.imgur.com/UX328.jpg I&a ...

Format the date using moment() for the last week of the current year and return it with the year. Next year's

I encountered an unusual problem when using Moment.js with Angular.js. When I use the .toISOString() method, I get the correct date, but when I use the .format() method, the date is completely wrong. Here is an example to illustrate the issue: Code snip ...

Tips for editing events in the "react-big-calendars" component

I am looking to implement a feature where users can click on events in a calendar and then edit either the dates or event titles. Can this functionality be achieved using "react-big-calendar"? If not, are there any other packages you can recommend? <Cal ...

You are unable to assign mutations in Vuex

Dealing with a peculiar problem where "val" and "ok" can be used within "console.log()", but for some reason, state.user cannot be assigned any value. However, state.user does display 'ok' on the website. export const state = () => ({ user: ...

Adding a fresh attribute to MongoDB using push model

I wrote a basic script that calculates the number of documents for a specific user and assigns it to externalUser.totalIcons. However, when I try to execute it, the model is not saved and the new property is not added to the database. My question is: wher ...

showing the data in a textbox using AJAX retrieved information

I have a table where additional rows can be added by the user with the click of a JavaScript function. Each row contains a drop down list, and based on the selected value, an AJAX script fetches some values to display in corresponding textfields within th ...

The form created using jQuery is not submitting correctly because the PHP $_FILES array is empty

Creating an HTML form dynamically in jQuery and submitting the form data via Ajax to 'add_sw.php' for processing is my current challenge. However, I have encountered an issue where the PHP script cannot access the PHP $_FILES variable as it turn ...