要比较属性,请使用$let和$indexOfArray。首先让我们创建一个包含文档的集合-
> db.demo366.insertOne( ... { ... ... "Name" : "Chris", ... "details" : [ ... { ... "Id" : "John1", ... "value" : "test" ... }, ... { ... "Id" : "John2", ... "value" : 18 ... }, ... { ... "Id" : "John3", ... "value" : 20 ... } ... ]} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e57ddd92ae06a1609a00ae7") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo366.find();
这将产生以下输出-
{ "_id" : ObjectId("5e57ddd92ae06a1609a00ae7"), "Name" : "Chris", "details" : [ { "Id" : "John1", "value" : "test" }, { "Id" : "John2", "value" : 18 }, { "Id" : "John3", "value" : 20 } ] }
以下是查询以比较MongoDB对象数组中不同对象的属性-
> db.demo366.find( ... {"$expr":{ ... "$let":{ ... "vars":{ ... "john2":{"$arrayElemAt":["$details",{"$indexOfArray":["$details.Id","John2"]}]}, ... "john3":{"$arrayElemAt":["$details",{"$indexOfArray":["$details.Id","John3"]}]} ... }, ... "in":{"$lt":["$$john2.value","$$john3.value"]}} ... }})
这将产生以下输出-
{ "_id" : ObjectId("5e57ddd92ae06a1609a00ae7"), "Name" : "Chris", "details" : [ { "Id" : "John1", "value" : "test" }, { "Id" : "John2", "value" : 18 }, { "Id" : "John3", "value" : 20 } ] }