gpt4 book ai didi

node.js - MongoDB : querying documents with two equal fields, $match 和 $eq

转载 作者:IT老高 更新时间:2023-10-28 13:10:29 25 4
gpt4 key购买 nike

如果我想要 document.a == document.b,返回集合中所有文档的最佳方式是什么?

我试过了

db.collection.aggregate([ { $match: { $eq: [ '$a', '$b' ] } }])

但它返回时没有错误或结果,因为我认为它实际上是匹配字符串“$a”和“$b”。是否有不同的方式来指定这些是字段?

db.collection.aggregate([    { $project: { 
eq: { $cond: [ { $eq: [ '$a', '$b' ] }, 1, 0 ] }
} },
{ $match: { eq: 1 } }])

上述方法可行,但需要额外的步骤,即使用它找到的任何文档再次查询或投影所有可能的字段。

有没有更好的方法来实现这个查询?

最佳答案

如果我理解你的问题,你想要那些在 field1 和 field2 中具有相同值的文档。

为了这次尝试

db.coll.find({$where: function() { return this.field1 == this.field2 } } );

或更紧凑

db.coll.find({ $where : "this.field1 == this.field2" } );

关于node.js - MongoDB : querying documents with two equal fields, $match 和 $eq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30762987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com