What is the process for setting values for a key by utilizing a value from a different key in a separate object within MongoDB?

Within my "users" collection, I have two objects named "user1" and "user2", each containing fields for avatar, friends, name, and potentially other information.

The crux of my question lies in the "friends" field within the "user2" object. This field is an array that includes an object {name: user1, avatar: db.users.user 1.avatar}. Essentially, I am aiming to establish a link to user1's avatar within this object in the avatar field.

To illustrate, imagine the following structure:

user1 : { avatar : "link on avatar", name: "user1", friends: [] },

user2 : { avatar : "link on avatar", name: "user1", friends: [{name: "user1", avatar: ??? }] }

Here, the question marks denote where the link to user1's avatar should be inserted.

I am seeking a way to achieve this directly in MongoDB without relying on Node.js for implementation.

I find myself uncertain about how to proceed with this task, as it presents a unique challenge given my constraints.

Answer №1

If you store the objectId in the friends array and then perform a $lookup operation

db.users.updateOne(
  {_id: new ObjectId("2")},
  {
    $push: {"friends": new ObjectId("1")}
  }
)

db.users.aggregate({
  $lookup:{
    from: "users",
    localField: "friends",
    foreignField: "_id",
    as: "friends"
  }
})

The result will be:

[
  {
    _id: ObjectId("1"),
    avatar: '1',
    name: 'user1',
    friends: []
  },
  {
    _id: ObjectId("2"),
    avatar: '2',
    name: 'user2',
    friends: [
      {
        _id: ObjectId("1"),
        avatar: '1',
        name: 'user1',
        friends: []
      }
    ]
  }
]

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

Issue with SCALA LIFT - Incorrectly saved model in mongo database

I am encountering an issue with my model setup. Here is the code snippet: class Mix private() extends MongoRecord[Mix] with ObjectIdPk[Mix] { def meta = Mix object title extends StringField(this, 50) object description extends StringField(th ...

Ways to determine the success of $wpdb->query and retrieve the outcome

Currently, I am in the process of developing a WordPress website, I have implemented a form that allows users to make modifications and update the database: Below is the HTML/PHP code snippet: echo '<form class="form-verifdoc" target=&q ...

Dropdown box with search functionality in twig

Here is the structure of my form: public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('Name') ->add('Occupation'); } This is what my edit.html.twig lo ...

Interconnected mongoose documents embedded within one another

I am working with a mongoDb database that consists of two collections: Collection: Category { id: catnumber: nameNL: nameFR: subcategories:[id:, nameNL:, nameFR] products:[id,nameNL,nameFR] } Collection: Product { id: nameNL: nameFR: description ...

Adding JSON data before the second to last element of an array:

I am looking to create a function that can consistently add JSON Items to an array just before the last item. const array = [ {India: { Score: '12', PlayedMatched: '21' } }, { China: { Score: '52', PlayedMatched: '51 ...

Exploring the Powerful Combination of GraphQL and MongoDB

I'm running into issues when trying to retrieve data from a mongodb database using both graphql and mongoose. Every time I query the database, it returns null, and no errors are being thrown. Here is the snippet of code in question: // Controller.js ...

Master the Art of Scrollbar Control in Angular!

I am currently developing a chat web application that functions similar to gchat. One of the key features I'm trying to implement is an alert notification when the scrollbar is in the middle of the div, indicating a new message. If the scrollbar is at ...

NodeJS Post Request Issue: Parsing Numbers in URL Parameters Resulting in NaN

I'm fairly new to working with NodeJS. Currently, I am facing an issue where all the integers in the parameters are being passed as NaN when making a POST request. In the snippet below, you can observe that the parameters have actual numbers assigned ...

Error: null does not have the property 'renderView' to be read

My goal is to set up a main page in React.js with two buttons: Option 1 and Option 2. Clicking on Option 1 should redirect the user to the Main1 page, while clicking on Option 2 should lead them to Main2. It seems straightforward, but I am encountering the ...

Dynamically load scripts in angularJs

Having multiple libraries and dependencies in my angularjs application is posing a challenge as I want to load them all using just one script, given that three apps are utilizing these dependencies. Currently, I have this custom script: var initDependenci ...

CSS: elements that are only visible when positioned above specific elements

Can we create an element that is only visible above specific other elements? For instance, in the following code snippet, I want the .reflection element to be visible only above the .reflective elements (located at the top and bottom) and not visible on t ...

Viewing a live gstreamer feed within a web browser

Seeking advice on how to integrate a camera feed from a Linux machine into a gstreamer pipeline for display in a web browser. Currently, I am developing an HTML/JavaScript interface to control the camera and communicate with a local server. However, I am f ...

Error: Attempting to access property 'propeller' of an undefined object has caused a TypeError

I am working on a tutorial that can be found at this link: https://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/ During the process, I encountered an error message: Uncaught TypeError: Cannot read property 'propeller& ...

What is the best way to pause a JavaScript JSON stream for 60 seconds?

I have been tasked with creating a JavaScript program that retrieves an API JSON record from a specific address every minute through a WebSocket. The stream should continue after 60 seconds, and I need to return both the current stream and the previous one ...

Utilizing middleware with express in the proper manner

Hello there! I'm just double-checking to see if I am using the correct method for implementing middleware in my simple express app. Specifically, I am trying to ensure that the email entered during registration is unique. Here's an example of wha ...

Decode special characters in the data returned from an ajax request

When making an ajax request with dataType: 'json', I encountered a problem. The json data received is well formed, but the strings in it have newlines escaped. For example, '{ "a" : "x\\r\\nx" }' As a result, th ...

Sending data from Django's render() method to React.js

Currently, I'm working on a Django + React Application project where I am faced with the challenge of passing JSON data from Django's render() function to React.js. To achieve this, I initiate the rendering of an HTML page using Django, with the ...

Incorporating dynamic images into Laravel using Angular

I am currently trying to dynamically input the src value of an image using Angular. Below is the code I have written : HTML : <div ng-app="myApp" ng-controller="MyCtrl"> <img src="{{asset('assets/img/'.'/'. @{{ item.name ...

Ways to fix the issue: Error message asking for a callback function for req#logout

I encountered an error while attempting to log out: "Error: req#logout requires a callback function at req.logout.req.logOut (C:\FrontEnd\web\2023\Login\node_modules\passport\lib\http\request.js:65:44) ...

How can you determine if a string includes all the words listed in a multidimensional array?

I'm brand new to the world of coding but I have a specific goal in mind. Here's an example of the multidimensional array I'm working with: var requiredProducts = [{ product: 'PRODUCT 1', keywords: ['KEYWORD1', & ...