我的蠢货:
[{
"_id":"621c6e805961def3332bcf97",
"title":"monk plus",
"brand":"venture electronics",
"category":"earphones",
"variant":[
{
"price":1100,
"impedance":"16ohm"
},
{
"price":1600,
"impedance":"64ohm"
}],
"salesCount":185,
"buysCount":182,
"viewsCount":250
},
{
"_id":"621c6dab5961def3332bcf92",
"title":"nokia1",
"brand":"nokia",
"category":"mobile phones",
"variant":[
{
"price":10000,
"RAM":"4GB",
"ROM":"32GB"
},
{
"price":15000,
"RAM":"6GB",
"ROM":"64GB"
},
{
"price":20000,
"RAM":"8GB",
"ROM":"128GB"
}],
"salesCount":34,
"buysCount":21,
"viewsCount":80
}]预期产出
[{
_id:621c6e805961def3332bcf97
title:"monk plus"
brand:"venture electronics"
category:"earphones"
salesCount:185
viewsCount:250
variant:[
{
price:1100
impedance:"16ohm"
}]
}]我尝试过这种聚合方法
[{
$match: {
'variant.price': {
$gte: 0,$lte: 1100
}
}},
{
$project: {
title: 1,
brand: 1,
category: 1,
salesCount: 1,
viewsCount: 1,
variant: {
$filter: {
input: '$variant',
as: 'variant',
cond: {
$and: [
{
$gte: ['$$variant.price',0]
},
{
$lte: ['$$variant.price',1100]
}
]
}
}
}
}}]此方法返回预期输出,现在我的问题是,是否还有其他更好的方法提前返回预期的output.Moreover感谢您,并且由于我对nosql数据库还不熟悉,所以我很想从community.Take中了解一个关于预期输出的说明--特定文档的所有属性必须只返回我想要根据价格筛选的对象的变量数组。
发布于 2022-03-01 18:15:55
聚合管道没有什么问题,还有其他方法可以做到。如果您只想返回匹配的文档,使用只返回第一个匹配的数组元素,下面是另一种方法。(不幸的是,.$语法只返回第一个匹配。)
db.collection.find({
// matching conditions
"variant.price": {
"$gte": 0,
"$lte": 1100
}
},
{
title: 1,
brand: 1,
category: 1,
salesCount: 1,
viewsCount: 1,
// only return first array element that matched
"variant.$": 1
})在mongoplayground.net上试一试。
或者,如果要使用聚合管道并返回除筛选数组以外的所有匹配文档,则可以使用"$set" (或别名"$addFields")“覆盖”所需的元素。这样做意味着您不需要"$project"任何东西。
db.collection.aggregate([
{
"$match": {
"variant.price": {
"$gte": 0,
"$lte": 1100
}
}
},
{
"$set": {
"variant": {
"$filter": {
"input": "$variant",
"as": "variant",
"cond": {
"$and": [
{ "$gte": [ "$$variant.price", 0 ] },
{ "$lte": [ "$$variant.price", 1100 ] }
]
}
}
}
}
}
])在mongoplayground.net上试一试。
发布于 2022-02-28 23:30:30
您的解决方案很好,只需确保在应用此步骤以获得更快的查询之前应用$match和分页即可。
https://stackoverflow.com/questions/71298057
复制相似问题