MongoDB如何比较关联数组中的字段
我在MongoDB中寻找正确的查询来比较关联数组中的两个值,我有如下文档:MongoDB如何比较关联数组中的字段,mongodb,nosql,Mongodb,Nosql,我在MongoDB中寻找正确的查询来比较关联数组中的两个值,我有如下文档: { "_id" : ObjectId("5502cc4280ee2cd549dee9e8"), "formats" : [ { "name" : "first", "prices" : [ { "futurePrice" : 5.49,
{
"_id" : ObjectId("5502cc4280ee2cd549dee9e8"),
"formats" : [
{
"name" : "first",
"prices" : [
{
"futurePrice" : 5.49,
"price" : 5.49
}
]
},
{
"name" : "second",
"prices" : [
{
"futurePrice" : 5.49,
"price" : 5.49
}
]
}
]
}
Collection.find({'formats.prices': { $elemMatch: 'this.futurePrice > this.price' }}, ...
我需要比较futurePrice和price字段,找到至少有一种格式的文档,格式为futurePrice>price
我试过这样的方法:
{
"_id" : ObjectId("5502cc4280ee2cd549dee9e8"),
"formats" : [
{
"name" : "first",
"prices" : [
{
"futurePrice" : 5.49,
"price" : 5.49
}
]
},
{
"name" : "second",
"prices" : [
{
"futurePrice" : 5.49,
"price" : 5.49
}
]
}
]
}
Collection.find({'formats.prices': { $elemMatch: 'this.futurePrice > this.price' }}, ...
但是它似乎不起作用,你知道吗?你可以使用聚合框架使用操作符:
db.Testing.aggregate([
{
'$unwind': '$formats'
},
{
'$unwind': '$formats.prices'
},
{
'$project':
{
formats :1,
eq : {
$cond: [ { $gt: [ '$formats.prices.futurePrice', '$formats.prices.price' ] }, 1, 0 ]
}
}
},
{
$match: { eq: 1 }
},
{
'$group':
{
'_id' : '$_id',
'formats':
{
'$push': '$formats'
}
}
}
])
编辑:
正如注释中提到的@pepkin88,您可以使用运算符获得相同的结果。尽管它没有利用索引,可能会影响性能
db.Testing.find(function() {
for (i = 0; i < this.formats.length; i++) {
for (j = 0; j < this.formats[i].prices.length; j++)
return this.formats[i].prices[j].futurePrice > this.formats[i].prices[j].price
}
})
db.Testing.find(函数(){
对于(i=0;i此。格式[i]。价格[j]。价格
}
})
可以,使用$where
操作员。它没有经过优化,也没有使用索引,但很有效。@pepkin88你说得对。谢谢你指出这一点。我将相应地修改我的答案。