Mongodb 如何在mongo db中的数组字段上进行逻辑操作$or
在MongoDB集合中,我在聚合后有一些数据:Mongodb 如何在mongo db中的数组字段上进行逻辑操作$or,mongodb,aggregation-framework,Mongodb,Aggregation Framework,在MongoDB集合中,我在聚合后有一些数据: { "_id" : ObjectId("5411e00c0d42e2a3688b47d3"), "found" : [false, false, false, false], } 如果有任何元素被设置为true,我如何在数组“found”上执行逻辑OR,以获得true,如果所有元素都是false 我正在尝试,但它总是返回true: db.test.aggregate( { $project: {
{
"_id" : ObjectId("5411e00c0d42e2a3688b47d3"),
"found" : [false, false, false, false],
}
如果有任何元素被设置为true
,我如何在数组“found”上执行逻辑OR,以获得true
,如果所有元素都是false
我正在尝试,但它总是返回true
:
db.test.aggregate( {
$project:
{
found: { $or: "$found" }
}
});
// "result" : [
// {
// "_id" : ObjectId("5411e00c0d42e2a3688b47d3"),
// "found" : true
// }
// ],
db.test.aggregate({
$project: {
like: { $anyElementTrue: ["$found"] }
}
});
另外,我正在使用MongoDB 2.6从2.6版开始,您可以使用
$anyElementTrue
:
db.test.aggregate( {
$project:
{
found: { $or: "$found" }
}
});
// "result" : [
// {
// "_id" : ObjectId("5411e00c0d42e2a3688b47d3"),
// "found" : true
// }
// ],
db.test.aggregate({
$project: {
like: { $anyElementTrue: ["$found"] }
}
});
见此:
如果您使用的是早期版本,那么恐怕您将不得不使用map/reduce或$unwind->$group
组合。诸如此类:
db.test.aggregate([
{
$unwind: "found"
},
{
$group: {
_id: "_id",
like: { $or: "found" }
}
}
]);
在您的情况下(使用$or)db.test.find({“find”:true})
可以正常工作