Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Find a document by INC value in MongoDB

From my website client I am sending an API request to the backend Node.js server and finding a specific document by ID like so:

var ObjectID = require('mongodb').ObjectID;   

db.collection('users').find({"_id": new ObjectID(req.body._id)})

Where req.body._id equals the entire ID string, such as '5d0381ad681a2a3aa1dc5872'

However I would prefer to send only the INC (ever incrementing value) portion of the string as the argument: 'c5872'

How should I find a specific document based on just the INC value? (I'm assuming the INC is unique)

Any help is greatly appreciated.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can temporarily transform your _id using in a string to be able to use a regular expression :

db.users.aggregate([
  {
    $addFields: { id: { $toString: '$_id' } }
  },
  {
    $match: { id: /c5872$/ }
  }
])

A cleaner solution is to create the field directly with a substring to avoid using a regular expression :

db.users.aggregate([
  {
    $addFields: { id: { $substr: [{ $toString: '$_id' }, 19, 24] } }
  },
  {
    $match: { id: 'c5872' }
  }
])

https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/ https://docs.mongodb.com/manual/reference/operator/aggregation/substr/

over 4 years ago · Santiago Trujillo Report

0

You could create an additional ID field and a unique index to ensure that indexed fields do not store duplicate values, but note that for a five hex string, we have "1,048,576" possible combinations (16 ^ 5 = 1048576).

Note: Using a regular expression could lead to a collection scan.

A regular expression is a "prefix expression" if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc.*/ will be optimized by matching only against the values from the index that start with abc.

Regular expression and index use

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!