猫鼬如何找到一个实例及其collection的所有唯一属性?
Mongoose how to find all unique properties of an instance and its collection?
我有一条collection这样的裤子:
{
color: 'Red',
'material': 'Cotton',
size: '33x44'
},
{
color: 'Red',
material: 'Cotton',
size: '38x46'
} // etc.
是否可以创建一个查询,其中 returns 所有未更改的信息(material
和 color
)以及所有更改的属性变体的列表(size
).
我猜这看起来像:
Shirts.find(sizes, {color: 'Red'}, function (err, sizes) {
// Just pseudocode here
}).distinct()
但这只是对伪代码的一次非常粗略的尝试。
像下面这样的聚合查询将为您提供按颜色分组的红色的唯一尺寸和 material。
Shirts.aggregate([
{$match: {color: 'Red'}},
{$group: {_id: {color: '$color', material: '$material'}, sizes: {$addToSet: '$size' }}}
], function (err, result)) {
console.log(result);
});
输出如下:
{
[
{
_id: {
color: 'Red',
material: 'Cotton'
},
sizes: [
'33x44',
'34x86'
]
}
]
}
我有一条collection这样的裤子:
{
color: 'Red',
'material': 'Cotton',
size: '33x44'
},
{
color: 'Red',
material: 'Cotton',
size: '38x46'
} // etc.
是否可以创建一个查询,其中 returns 所有未更改的信息(material
和 color
)以及所有更改的属性变体的列表(size
).
我猜这看起来像:
Shirts.find(sizes, {color: 'Red'}, function (err, sizes) {
// Just pseudocode here
}).distinct()
但这只是对伪代码的一次非常粗略的尝试。
像下面这样的聚合查询将为您提供按颜色分组的红色的唯一尺寸和 material。
Shirts.aggregate([
{$match: {color: 'Red'}},
{$group: {_id: {color: '$color', material: '$material'}, sizes: {$addToSet: '$size' }}}
], function (err, result)) {
console.log(result);
});
输出如下:
{
[
{
_id: {
color: 'Red',
material: 'Cotton'
},
sizes: [
'33x44',
'34x86'
]
}
]
}