这是我在数据库中的示例文档。
{
"_id":1,
"object":{
"featureOne":true,
"featureTwo":false,
"featureThree":false,
"featureFour":false
}
}, {
"_id":2,
"object":{
"featureOne":false,
"featureTwo":false,
"featureThree":false,
"featureFour":false
}
}, {
"_id":3,
"object":{
"featureOne":true,
"featureTwo":false,
"featureThree":false,
"featureFour":false
}
}
我想在单个查询中获得一个带有 "featureOne": true 的对象和另一个带有 "featureOne": false 的对象。我知道如何使用特定键和值查找数据。但是如何在单个查询中使用相同的 true 和 false 值键获取数据。现在我正在使用这段代码
db.collection(collectionName).find({"featureOne":true, {limit:1}).toArray(function(err, results) {
db.collection(collectionName).find("featureOne":,false{limit:2}).toArray(function(err,res {
console.log(results,res);
});
});
有没有更好的方法来实现这一点?
最佳答案
您可以使用聚合框架来实现它。
您可以使用 $group和 $project阶段(如 Clement Amarnath 回答中所述),但如果您需要对数据收集阶段进行更多控制,则可以使用:
- > $facet - 通过子聚合管道收集数据。
- > $match - 设置文档过滤器的标准。
- > $limit - 定义可以获取的最大文档数量(如果要随机化结果,请使用 $sample)。
- > $addFields - 将结果合并到一个元素(数组)中。
- > $unwind - 拆分结果 数组到单独的文档中。
- > $replaceRoot - 更改文件 根元素。
示例代码:
db.collection.aggregate([
{
$facet: {
"result1": [
{$match: {"object.featureOne": true}},
{$limit: 1}
],
"result2": [
{$match: {"object.featureOne": false}},
{$limit: 1}
]
}
},
{$addFields: {"results": [{$arrayElemAt: ["$result1", 0]}, {$arrayElemAt: ["$result2", 0]}]}},
{$unwind: "$results"},
{$replaceRoot: {newRoot: "$results"}}
])
关于javascript - 使用 JavaScript 在 mongoDb 中查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47628094/