请教,在mongodb的查询中如何引用文档(记录)中的key值?
发布于 2年前 作者 hinode 1215 次浏览

比如:有如下文档: {a:2,b:3}

如何在查询条件中引用key b的值呢?比如我想做:

find({a:{$gt:b+1}}),但是这样,会提示b没有定义,当然这个例子可以用$where去实现。

但是我只是想知道如何引用b的值,谢谢!

5 回复

我希望拿到key值在条件中做运算,谢谢。

有想法,不过很难实现,印象中每看过类似的api,找到可以通知我

貌似这种情况只能用where,摘自官网doc:

Use the $where operator to pass a string containing a JavaScript expression to the query system to provide greater flexibility with queries. Consider the following:

db.collection.find( { $where: "this.a == this.b" } );

$where evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g., $gt, $in).

In general, you should use $where only when you can’t express your query using another operator. If you must use $where, try to include at least one other standard query operator to filter the result set. Using $where alone requires a table scan.

看来真的只能$where了,多谢两位的关注和回答。

我想我还是在插入文档的时候,修改文档结构吧,先做出运算结果以方便今后的查询。

回到顶部