筛选包含Sold状态且价格全为0/null的对象数组的文档
需求说明
现有一批文档,每个文档内包含records对象数组,数组中的每个对象有以下三个字段:
records.saleStatus:记录的销售状态records.price.firstprice:第一价格records.price.secondPrice:第二价格
常规规则为:若记录的saleStatus为"Sold",则price下至少有一个价格(firstprice或secondPrice)非0且非null。现在需要筛选出包含违反该规则的记录的文档,即文档中存在至少一条records元素满足:
saleStatus == "Sold" 并且 (firstprice是0或null) 并且 (secondPrice是0或null)
示例展示
输入文档示例
[ { "id": "doc1", "records": [ { "saleStatus": "Sold", "price": { "firstprice": 100, "secondPrice": null } }, { "saleStatus": "Sold", "price": { "firstprice": 0, "secondPrice": null } } ] }, { "id": "doc2", "records": [ { "saleStatus": "Unsold", "price": { "firstprice": 0, "secondPrice": null } } ] } ]
期望输出结果
[ { "id": "doc1", "records": [ { "saleStatus": "Sold", "price": { "firstprice": 100, "secondPrice": null } }, { "saleStatus": "Sold", "price": { "firstprice": 0, "secondPrice": null } } ] } ]
解释:doc1包含一条违反规则的Sold状态记录,因此被筛选出来;doc2的记录为Unsold状态,不受常规规则约束,所以被排除。
常见实现示例(以MongoDB为例)
如果使用MongoDB完成该筛选,可通过find搭配$elemMatch实现:
db.collection.find({ "records": { "$elemMatch": { "saleStatus": "Sold", "price.firstprice": {"$in": [0, null]}, "price.secondPrice": {"$in": [0, null]} } } })
该语句会精准匹配出所有包含目标违规记录的文档。
内容的提问来源于stack exchange,提问作者Ashish
相关产品推荐
相关产品推荐

