如何查找文档并使用聚合在mongodb中找到一个属性?
How to find documents and use aggregate to find a property in mongodb?
我在一个集合中有数千个文档。以下是示例文档
{
_id: 12345,
createdDate: "2020-07-10",
cars: [
{
type: "Sedan",
engine: [
{
type: "Petrol",
power: 150,
brake: {
type: "Disc",
hasABS: false
}
},
{
type: "Petrol",
power: 190,
brake: {
type: "Drum",
hasABS: false
}
},
{
type: "Diesel",
power: 160,
brake: {
type: "Disc",
hasABS: true
}
}
]
},
{
type: "SUV",
engine: [
{
type: "Petrol",
power: 150,
brake: {
type: "Disc",
hasABS: false
}
},
{
type: "Petrol",
power: 190,
brake: {
type: "Drum",
hasABS: false
}
},
{
type: "Diesel",
power: 160,
brake: {
type: "Disc",
hasABS: true
}
}
]
}
]
}
现在我想查找在 7 月份创建的汽车,并汇总以查找带 abs 刹车的汽车
下面是我的查询:
db.getCollection('collection')
.find({
$and: [
{"createdDate": {"$gte": new Date("2020-07-01"), "$lt": new Date("2020-07-10")}},
aggregate(
{"$unwind": "$cars"},
{"$unwind": "$cars.engine"},
{"$match": {"cars.engine.brake.hasABS": true}},
{"$project": {"cars": 1}},
{"$group": {"_id": "$cars"}}
)
]
})
.pretty()
当我尝试 运行 上述查询时,出现错误。这是应该怎么做还是有更好的方法?
您不能同时使用 .find()
和 .aggreate()
。在这种情况下,您可以在 $match 聚合阶段使用相同的过滤器:
db.collection.aggregate([
{ $match: { createdDate: { $gte: "2020-07-01", $lt: "2020-07-10" } } }, // or { "$gte" : new Date("2020-07-01"), "$lte" : new Date("2020-07-10") }
{ "$unwind": "$cars" },
{ "$unwind": "$cars.engine"},
{ "$match": {"cars.engine.brake.hasABS" : true}}
])
我在一个集合中有数千个文档。以下是示例文档
{
_id: 12345,
createdDate: "2020-07-10",
cars: [
{
type: "Sedan",
engine: [
{
type: "Petrol",
power: 150,
brake: {
type: "Disc",
hasABS: false
}
},
{
type: "Petrol",
power: 190,
brake: {
type: "Drum",
hasABS: false
}
},
{
type: "Diesel",
power: 160,
brake: {
type: "Disc",
hasABS: true
}
}
]
},
{
type: "SUV",
engine: [
{
type: "Petrol",
power: 150,
brake: {
type: "Disc",
hasABS: false
}
},
{
type: "Petrol",
power: 190,
brake: {
type: "Drum",
hasABS: false
}
},
{
type: "Diesel",
power: 160,
brake: {
type: "Disc",
hasABS: true
}
}
]
}
]
}
现在我想查找在 7 月份创建的汽车,并汇总以查找带 abs 刹车的汽车
下面是我的查询:
db.getCollection('collection')
.find({
$and: [
{"createdDate": {"$gte": new Date("2020-07-01"), "$lt": new Date("2020-07-10")}},
aggregate(
{"$unwind": "$cars"},
{"$unwind": "$cars.engine"},
{"$match": {"cars.engine.brake.hasABS": true}},
{"$project": {"cars": 1}},
{"$group": {"_id": "$cars"}}
)
]
})
.pretty()
当我尝试 运行 上述查询时,出现错误。这是应该怎么做还是有更好的方法?
您不能同时使用 .find()
和 .aggreate()
。在这种情况下,您可以在 $match 聚合阶段使用相同的过滤器:
db.collection.aggregate([
{ $match: { createdDate: { $gte: "2020-07-01", $lt: "2020-07-10" } } }, // or { "$gte" : new Date("2020-07-01"), "$lte" : new Date("2020-07-10") }
{ "$unwind": "$cars" },
{ "$unwind": "$cars.engine"},
{ "$match": {"cars.engine.brake.hasABS" : true}}
])