要在MongoDB中连接条件,请使用$cond,然后在其中使用$concat。让我们创建一个包含文档的集合-
> db.demo745.insertOne({Value1:"100",Value2:"100"}); { "acknowledged" : true, "insertedId" : ObjectId("5eae6419a930c785c834e554") } > db.demo745.insertOne({Value1:"40",Value2:"50"}); { "acknowledged" : true, "insertedId" : ObjectId("5eae6421a930c785c834e555") } > db.demo745.insertOne({Value1:"13",Value2:"45"}); { "acknowledged" : true, "insertedId" : ObjectId("5eae6429a930c785c834e556") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo745.find();
这将产生以下输出-
{ "_id" : ObjectId("5eae6419a930c785c834e554"), "Value1" : "100", "Value2" : "100" } { "_id" : ObjectId("5eae6421a930c785c834e555"), "Value1" : "40", "Value2" : "50" } { "_id" : ObjectId("5eae6429a930c785c834e556"), "Value1" : "13", "Value2" : "45" }
以下是要与条件连接的查询-
> db.demo745.aggregate( ... [ ... { "$redact": { ... "$cond": [ ... { "$eq": [ ... { "$concat": [ "$Value1","$Value2" ] }, ... "1345" ... ]}, ... "$$KEEP", ... "$$PRUNE" ... ] ... }} ... ] ... )
这将产生以下输出-
{ "_id" : ObjectId("5eae6429a930c785c834e556"), "Value1" : "13", "Value2" : "45" }