也许标题不够。下面我来解释一下。
假设我的数据库结构为
{
name: "alex",
age: "21",
location: "university-alex"
}
我知道这个数据库结构不合理,但我只想以最短的方式展示我的问题。
我想获取
location
包含 name
字段值的文档。这里 university-alex
包括 , alex
所以它应该作为查询的结果返回。到目前为止我做了什么?
我写了这个查询,但无法得到结果。
db.collection.find({location: {$regex: "$name"}})
我怎样才能编辑它?
最佳答案
我认为您可以使用 $where
运算符来实现您想要实现的目标。
根据 this part of the documentation
db.collection.find({ $where: function() {
return (this.location.includes(this.name));
} } );
或者您可以将 JS 表达式传递给 find 方法:
db.collection.find(function() {
return (this.location.includes(this.name));
});
希望能帮助到你,
此致
关于node.js - 如何编写使用文档中两个字段的查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43806940/