如何在文档中使用两个字段的地方编写查询
也许标题是不够的。 在这里让我解释一下。
假设我有数据库结构
{ name: "alex", age: "21", location: "university-alex" }
我知道这个数据库结构是不合理的,但我只想以最短的方式显示我的问题。
我想获取location
包含name
字段值的文档。 这里university-alex
包括alex
所以它应该作为查询的结果返回。
我到目前为止做了什么? 我写了这个查询,但无法得到结果。
db.collection.find({location: {$regex: "$name"}})
我如何编辑它?
我想你试图实现可以用$where
操作符来完成。 根据这部分的文件
db.collection.find({ $where: function() { return (this.location.includes(this.name)); } } );
或者,您可以将JSexpression式传递给find方法:
db.collection.find(function() { return (this.location.includes(this.name)); });
希望能帮助到你,
最好的祝福
@boehm_s答案的一部分是可行的,非常清晰,你也可以创build一个多字段索引,你可以用它来find你需要的东西。 如果要执行组合查询方法,这种索引非常有用,例如,如果传入的参数与其内容匹配或包含在其中,则查找多个string
字段。 你可以看看这个关于文本索引的文档页面。 我不知道你是否使用Mongoose
,但这个答案可能是有用的。
请注意这样一个事实,即我的这种方法将返回所有包含在一个或两个字段中的文档,即您正在查找的“单词”。
在你的领域创build索引后
db.collection.createIndex( { name: "text", location: "text" } )
假设你已经命名了这个索引txtIndex
,那么你可以这样做
Mongo Driver for Node Way
. . . 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方式
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); }); }