mongo中的组不包括零值
我有Mongo查询,可以在文档上进行组操作。
我几乎得到了预期的结果,除了我想在没有空值或空值的情况下完善结果。
目前,我的查询看起来像这样:
db.productMetadata.aggregate([{$group:{"_id":{"color":"$productAttribute.colour","gender":"$productAttribute.gender"},"count" : {$sum : 1}}}]);
结果看起来像这样:
{ "_id" : { "color" : "BLUE", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { }, "count" : 4 }
{ "_id" : { "color" : "NA", "gender" : "WOMEN" }, "count" : 1 }
{ "_id" : { "color" : "BLACK", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "BROWN", "gender" : "WOMEN" }, "count" : 1 }
{ "_id" : { "gender" : "MEN" }, "count" : 2 }
{ "_id" : { "color" : "BEIGE", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "BROWN", "gender" : "MEN" }, "count" : 1 }
如果元素值均为空或db的实际数据中,我想删除行。
例外的结果应该看起来像这样:
{ "_id" : { "color" : "BLUE", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "NA", "gender" : "WOMEN" }, "count" : 1 }
{ "_id" : { "color" : "BLACK", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "BROWN", "gender" : "WOMEN" }, "count" : 1 }
{ "_id" : { "color" : "BEIGE", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "BROWN", "gender" : "MEN" }, "count" : 1 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要一个额外的“ $ productattribute.colour” 现有而不是null的步骤,而不是null:
You need an extra
$match
pipeline step that will filter the incoming documents based on the embedded field"$productAttribute.colour"
existing and not null:此示例包括两个不同的集合。为此,我们使用聚合功能。我还在使用Mongoose ,
$ $ project to重命名字段以正确显示在客户端
。
异步GetAllmasterDataCustomFields(req){
。
this example includes two different Collections. For this we use aggregate function. I am also using Mongoose
$project to rename the Fields to show properly on the client
.
async getAllMasterDataCustomFields(req) {
.
也许您应该使用$ match:{'color':{$存在:true}} $ group操作之前。使用稀疏索引,它将很快起作用。
并且不要将“ null”字段存储在集合中,这将降低数据库的大小,并会提高稀疏索引(索引中的文档更少 - >更速度)
Perhaps you should use $match: {'color': {$exists: true}} before $group operation. With sparse index it will work pretty fast.
And do not store "null" fields in collections at all, that will reduce db size and will increase search speed for sparse indexes (less documents in index -> more speed)