MongoDB:如何判断对象中是否存在指定数组
处理含多类型关联数组的产品集合
嘿,我处理过不少这类电商数据集,你提到的ar_related字段确实是用来捕捉用户行为关联的核心字段,它的结构设计很贴合电商场景下的产品推荐需求——允许存储0个或多个不同的关联数组,比如also_viewed、also_bought、bought_together、buy_after_viewing这些。
先给你补全一下文档示例,让结构更清晰:
{ "_id" : ObjectId("5a95cef390bd8fbf1c699d6d"), "ar_asin" : "0078764343", "ar_description" : "Brand new sealed!", "ar_price" : 37.98, "ar_imUrl" : "http://ecx.images-amazon.com/images/I/513h6dPbwLL._SY300_.jpg", "ar_related" : { "also_viewed": ["B001XYZ", "B002ABC"], "also_bought": ["B003DEF"], "bought_together": ["B004GHI", "B005JKL", "B006MNO"], "buy_after_viewing": [] } }
常见的字段操作示例
针对这个字段,我整理了几个日常处理中常用的操作(以MongoDB为例,其他数据库逻辑类似):
查询存在特定关联类型的文档:如果想找出所有有
also_bought关联且不为空的产品,可以用:db.products.find({ "ar_related.also_bought": { $exists: true, $ne: [] } })提取单个关联类型的数据:如果只需要每个产品的
also_viewed列表和对应的ASIN,可以用投影过滤:db.products.find({}, { "ar_related.also_viewed": 1, ar_asin: 1, _id: 0 })统计各关联类型的覆盖情况:要统计有多少产品包含每种关联类型,可以用聚合管道:
db.products.aggregate([ { $project: { has_also_viewed: { $cond: [{ $gt: [{ $size: "$ar_related.also_viewed" }, 0] }, 1, 0] }, has_also_bought: { $cond: [{ $gt: [{ $size: "$ar_related.also_bought" }, 0] }, 1, 0] }, has_bought_together: { $cond: [{ $gt: [{ $size: "$ar_related.bought_together" }, 0] }, 1, 0] }, has_buy_after_viewing: { $cond: [{ $gt: [{ $size: "$ar_related.buy_after_viewing" }, 0] }, 1, 0] } } }, { $group: { _id: null, total_also_viewed: { $sum: "$has_also_viewed" }, total_also_bought: { $sum: "$has_also_bought" }, total_bought_together: { $sum: "$has_bought_together" }, total_buy_after_viewing: { $sum: "$has_buy_after_viewing" } } } ])
内容的提问来源于stack exchange,提问作者Ashley Redman BSc
相关产品推荐
相关产品推荐

