标题可能还不够。在这里让我解释一下。
假设我的数据库结构为
{
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/