Determine the Value of Bitwise Operators

My ranks collection includes a permissions field that uses bitwise operators:

[
  {
    "_id": "xxxx",
    "name": "Rank 1",
    "permissions": 1
  },
  {
    "_id": "xxxxxxxxx",
    "name": "Rank 2",
    "permissions": 2
  }
]

Here are some example users:

[
   {
      "_id":"1234",
      "ranks":[
         "xxxx",
         "xxxxxxxxx"
      ]
   }
]

In the users collection, there is a ranks value that holds an array of rank ids.

I am looking to retrieve the user along with their ranks and set their permissions to a certain value.

const users = await this.collection.aggregate([
    {
        $match: { userID: '123' }
    },
    { $limit: 1 },
    {
        $lookup: {
            from: 'ranks',
            localField: 'rank',
            foreignField: '_id',
            as: 'ranks'
        }
    },
    {
        $set: {
            permissions: {
                $arrayElemAt: ['$rank.permissions', 0]
            }
        }
    },
    {
        $unwind: {
            path: '$rank',
            preserveNullAndEmptyArrays: true
        }
    }
]).toArray();

This currently retrieves only one value from the collection, but I want to get all permissions and combine the bitwise operators together.

Desired Output

{
   "_id": "1234",
   "ranks":[
        "xxxx",
        "xxxxxxxxx"
   ]
   "permissions":3
}

Any assistance would be greatly appreciated!

Answer №1

Here is a method to combine all the rank permissions using server-side JavaScript through the use of "$function".

db.users.aggregate([
  {
    "$match": {
      "_id": 42
    }
  },
  {
    "$lookup": {
      "from": "ranks",
      "localField": "ranks",
      "foreignField": "_id",
      "pipeline": [
        {
          "$project": {
            "_id": 0,
            "permissions": 1
          }
        }
      ],
      "as": "permissions"
    }
  },
  {
    "$set": {
      "permissions": {
        "$function": {
          "body": "function(perms) {return perms.reduce((prevValue, currValue) => prevValue | currValue, 0)}",
          "args": ["$permissions.permissions"],
          "lang": "js"
        }
      }
    }
  }
])

Give it a try on mongoplayground.net.

Answer №2

When it comes to collecting samples...

db = {
  "permissions": [
    {
      "_id": "xxxx",
      "name": "Rank 1",
      "permissions": 1
    },
    {
      "_id": "xxxxxxxxx",
      "name": "Rank 2",
      "permissions": 2
    },
    {
      "_id": "xxxxxxx",
      "name": "Rank 4",
      "permissions": 4
    }
  ],
  "users": [
    {
      "_id": "1234",
      "ranks": [
        "xxxx",
        "xxxxxxxxx"
      ]
    },
    {
      "_id": "4567",
      "ranks": [
        "xxxx",
        "xxxxxxx"
      ]
    }
  ]
}

...consider utilizing the following set of transformations, which...

  • Detects the _id for the user 1234 within the users database.
  • Finds all associated ranks in the permissions database.
  • Expands the data to produce an individual result per permissions association.
  • Combines the permissions and ranks.
db.users.aggregate([
  {
    $match: {
      "_id": "1234"
    }
  },
  {
    $lookup: {
      from: "permissions",
      localField: "ranks",
      foreignField: "_id",
      as: "ranks"
    }
  },
  {
    $unwind: "$ranks"
  },
  {
    $group: {
      _id: "$_id",
      ranks: {
        $push: "$ranks._id"
      },
      permissions: {
        $sum: "$ranks.permissions"
      }
    }
  }
])

For further exploration, check out the MongoDB playground available at...

Essential Reminder: This command groups the permissions by summation (as opposed to employing boolean logical OR), hence ensuring no duplicated permissions is crucial. In case guaranteeing unique permissions per user proves challenging, suggesting that the permissions are $pushed akin to the ranks, followed by executing post-processing on the permissions list to reduce via logical OR would be advisable...

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

Ways to update the content within an IFRAME using server-side methods

I've searched through many posts, but I still haven't found a clear solution to my problem. Here's what's going on: I have a page with an IFRAME that is pulling content from a different domain. The style of the frame doesn't match ...

Utilizing JSON Objects to Populate a Knockout Form

I am looking to populate a form using knockout data-binding from a JSON object. I currently have the values hardcoded in my knockout setup, but what I really want to achieve is dynamically populating the form based on a JSON object. Here is a link to my ...

What is the reason that try/catch cannot handle errors thrown in the Promise constructor?

My code is encountering an unhandledRejection error and I'm having trouble understanding why. If the Error is thrown within a try/catch block, shouldn't it be caught by the catch expression? async function main () { try { await run(throwEr ...

Form input using the div element (when clicked)

I am currently working on a page that connects to a database with user information. For each user, I am creating a separate div element so that there are 6 divs total (each representing a different user). My goal is to have the ability for a user to click ...

MongoDB: An excessive number of connections were established from mongos to shards during the index creation process

We have implemented a sharded cluster with a replica set for each shard in our production environment. However, we encountered an issue last night when trying to connect to the cluster and execute a building index command through the mongo shell by connect ...

Asynchronous task during stream processing

Can anyone assist me? I am looking to read a file as a stream and when processing the initial chunk, I need to create a database table in an async manner. To achieve this, I want to develop a duplex/transformer stream that would be responsible for creatin ...

What causes Vue to drop nested component data within a v-for loop?

Witness the mysterious behavior through my fiddles: Anticipated outcome: https://jsfiddle.net/o7c9mwzf/27/ By clicking "unshift," I add an element to the beginning of my items array. After setting its data, clicking "unshift" again should maintain the el ...

ng-repeat did not properly listen for changes in the radio box selection

Feeling a bit confused here. I'm trying to call a function on change and pass the obj to it. From what I understand, since it's bound to the selected obj, I should be able to just use ng-model. However, in this situation, nothing happens when I s ...

Discovering instructions on locating Material UI component documentation

I'm having trouble locating proper documentation for MUI components. Whenever I attempt to replicate an example from the site, I struggle to customize it to fit my requirements. There are numerous props used in these examples that I can't seem to ...

Benefits of Utilizing Object.create

Unlike the referenced question, this code snippet is sourced from the book "JavaScript: The Definitive Guide". It introduces an inherit method that applies Object.create if available, but falls back to traditional JavaScript inheritance when it's not. ...

Javascript window.scroll function malfunctioning in some browsers while running in localhost

Check out this codepen link where everything is working, but unfortunately not locally: https://codepen.io/LoudDesignStudios/pen/RwxPJKY <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> < ...

Unable to store the data retrieved from MySQL into an array

Every time I try to add the object result1 to the array a, it ends up empty. Can someone help me figure out what I'm doing wrong? app.get('/freezer', (req, res) => { var a = []; var sql = `SELECT freezer_id FROM freezer_data`; ...

What is the best way to eliminate the external pause button?

My website contains the following HTML snippet: <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="a ...

Ensuring safe access to a Vue.js single-page application

After following numerous Vue.js tutorials, I have encountered a dilemma. Imagine I am constructing a single-page application where a user can log in and access data through a RESTful API. The initial step involves sending login credentials (username and p ...

How can you use jQuery to target a textbox based on its value that includes quotation marks?

Dealing with a JavaScript string that includes a quote mark can cause some difficulties. For example, strings like Don't click this checkbox or He said "hi" pose unique challenges when trying to find an exact match in a checkbox value. Consider the H ...

Converting string literals to an array of enums

I have a scenario where I am getting the following data in an API response: { "roles": [ "ADMIN", "USER" ] } The response always includes an array of roles (USER, PRESENTER, ORGANIZER, and ADMIN). I am looking to transform this into a valid TypeScript a ...

Creating a Conditional "Retrieve Script File" Function in JavaScript Without Dependencies

At the company where I work, we have numerous clients with their own websites that are connected to our system through a linking mechanism. Essentially, these clients have a link on their website that directs users to our site upon clicking. I am working ...

Guide to using Ajax to send a form and receive text in response

Check out my code on Fiddle: $("form.signupform").submit(function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Added this line for reference $.post(url, data, function(data) { $(for ...

Having difficulty retrieving text from textarea with jquery

I'm experiencing an issue with my jquery script where the top two buttons are showing 'undefined' instead of performing the same action as the buttons below them. Could someone please pinpoint where I went wrong? I want the two buttons at t ...

Error Occurs: 'PRM_MissingPanel' randomly in Ajax Update Panel

When using the Ajax Update Panel in Visual Studio to handle post backs for my search function, I encounter an issue. After generating a gridview with the results (i.e., searching for a member), whenever I update to the newest version from TFS, an error is ...