How to write a query where it uses two fields in a document

Perhaps the title is not enough. Here let me explain.

Suppose I have a database structure like

{
    name: "alex",
    age: "21",
    location: "university-alex"
}

I know that this database structure is not rational, but I just want to show my problem in a short way.

I want to get documents where it locationcontains the field value name. university-alexIncludes here alex, so it should be returned as a result of the request.

What have i done so far? I wrote this query, but could not get the result.

db.collection.find({location: {$regex: "$name"}})

How can I edit it?

+4
source share
2 answers

, , , $where.

db.collection.find({ $where: function() { 
  return (this.location.includes(this.name)); 
} } );

JS find:

db.collection.find(function() { 
  return (this.location.includes(this.name)); 
});

, ,

0

@boehm_s , , , , . , , . string, . . , Mongoose , .

, , "", .

db.collection.createIndex(
   {
     name: "text",
     location: "text"
   }
 )

, txtIndex,

Mongo Node

. . .

let userProjection = {
    "name": 1,
    "age": 1,
    "location": 1
};

/**
 *  @param req Contains information to find a user
 *  @param req.findMe Contains name concatenated to location 
 */
let findUsers = (req) => {
    letUsers = db.collection('users');
    return new Promise((resolve, reject) => {
        User.findOne({'txtIndex': params.body.findMe}, {fields: userProjection},(err, user) => {
           if (err) {
               return reject({message: 'MongoDB Error', err: err});
           }
           if (!user) {
               return reject({message: 'User not found!'});
           }
               return resolve(user);
        });

    });
}

Mongoose Way

let Users = require('./users-model.js);

/**
  *  @param req Contains information to find a user
  *  @param req.findMe Contains name concatenated to location 
  */
let findUsers = (req) => {
   Users.findOne({txtIndex: req.body.FindMe}).then( function (err, user) {
         if (err) {
           return reject({message: 'MongoDB Error', err: err});
         }
         if (!user) {
           return reject({message: 'User not found!'});
         }
           return resolve(user);
    });    

}
0

Source: https://habr.com/ru/post/1676480/


All Articles