如何在MongoDB中比较字段值?
您可以使用$where运算符在MongoDB中比较字段值。首先让我们创建一个包含文档的集合
> db.comparingFieldDemo.insertOne({"Value1":30,"Value2":40});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c99ed2d6669774125246e")
}
> db.comparingFieldDemo.insertOne({"Value1":60,"Value2":70});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c99f62d6669774125246f")
}
> db.comparingFieldDemo.insertOne({"Value1":160,"Value2":190});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c99ff2d66697741252470")
}
> db.comparingFieldDemo.insertOne({"Value1":200,"Value2":160});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c9a0b2d66697741252471")
}以下是在find()方法的帮助下显示集合中所有文档的查询
> db.comparingFieldDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5c9c99ed2d6669774125246e"),
"Value1" : 30,
"Value2" : 40
}
{
"_id" : ObjectId("5c9c99f62d6669774125246f"),
"Value1" : 60,
"Value2" : 70
}
{
"_id" : ObjectId("5c9c99ff2d66697741252470"),
"Value1" : 160,
"Value2" : 190
}
{
"_id" : ObjectId("5c9c9a0b2d66697741252471"),
"Value1" : 200,
"Value2" : 160
}以下是通过比较字段值查找的查询。
> db.comparingFieldDemo.find({ $where: "this.Value1 > this.Value2" } );这将产生以下输出
{ "_id" : ObjectId("5c9c9a0b2d66697741252471"), "Value1" : 200, "Value2" : 160 }让我们看看另一个查询
> db.comparingFieldDemo.find({ $where: "this.Value1 < this.Value2" } );这将产生以下输出
{ "_id" : ObjectId("5c9c99ed2d6669774125246e"), "Value1" : 30, "Value2" : 40 }
{ "_id" : ObjectId("5c9c99f62d6669774125246f"), "Value1" : 60, "Value2" : 70 }
{ "_id" : ObjectId("5c9c99ff2d66697741252470"), "Value1" : 160, "Value2" : 190 }热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短