Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 769
Steve Avatar asked Apr 06 '21 04:04

Steve


1 Answers

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/

like image 56
Romain Simon Avatar answered Sep 19 '22 20:09

Romain Simon