zoukankan      html  css  js  c++  java
  • java mongoDB 二级数组嵌套查询

    场景:

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

    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();
    

      

  • 相关阅读:
    JS闭包中的循环绑定处理程序
    Java学习之路-Spring的HttpInvoker学习
    Java学习之路-Burlap学习
    Java学习之路-Hessian学习
    Java学习之路-RMI学习
    现代浏览器的工作原理
    Socket Connect问题
    Tair总述
    TCP协议解析
    数据结构 之 二叉堆(Heap)
  • 原文地址:https://www.cnblogs.com/jifeng/p/6075237.html
Copyright © 2011-2022 走看看