java mongoDB 二级数组嵌套查询

时间:2021-12-30 03:13:04

场景:

会员集合下有多个会员文档,会员文档下有多个订单文档,订单买了多个商品文档

member->orders>orderItems

要求:

通过会员id和商品id验证会员是否购买过该商品。

数据示例

{
"_id" : ObjectId("57e395c7a8a9b40d62008704"),
"orders" : [
{
"_id" : ObjectId("582d5633c8ddd70b75a7a050"),
"paid" : true,
"status" : "PAID",
"orderItems" : [
{
"ID" : ObjectId("582d5633c8ddd70b75a7a051"),
"requestId" : "582d5633c8ddd70b75a7a04f",
"price" : "4",
"ultimatePrice" : "4",
"quantity" : NumberInt("1")
}
]
}
]
}

  mongodb语句:

db.getCollection("f.member").find({_id:ObjectId("memberId……"),"orders.paid":true,"orders":{"$elemMatch":{"orderItems":{"$elemMatch" :{"ID":ObjectId("itemId……")}}}}},{"orders.$.orderItems":1})

  java代码:

BasicDBObject itemIdDbObject=new BasicDBObject("ID",itemId);
BasicDBObject itemsIdElem=new BasicDBObject().append(QueryOperators.ELEM_MATCH,itemIdDbObject);
BasicDBObject orderItemsElem=new BasicDBObject().append("orderItems",itemsIdElem);
BasicDBObject orderElem=new BasicDBObject().append(QueryOperators.ELEM_MATCH,orderItemsElem);
BasicDBObject fiedValue=new BasicDBObject();
fiedValue.put("_id",memberId);
fiedValue.put("orders.paid",true);
fiedValue.append("orders",orderElem);
BasicDBObject retrievedFields=new BasicDBObject("orders.$",1);
System.out.println(fiedValue.toJson());
DBCursor rs = this.getCollection().find(fiedValue);
DBObject explain = rs.explain();
int count = rs.count();