mongodb用子文档做为查询条件的两种方法

    {
      "_id": ObjectId("52fc6617e97feebe05000000"),
      "age": 28,
      "level": NumberInt(500),
      "name": "name5",
      "person": [
        {
          "level": 5,
          "score": 100,
        "ccc":{"ccc3":56,"fff3":78}
        },
        {
          "level": 7,
          "score": 90,
          "like": "music"
        }
      ],
      "score": NumberInt(500),
      "sex": "男"
    }

  方法一:

db.testColl.find({"person.level":7});

db.testColl.find({"person.ccc.ccc3":56});

  

均可查出结果,就是说这种方法可以嵌套使用!

方法二、使用$elemMatch操作符

db.testColl.find({"person":{"$elemMatch":{"level":5}}});

  

可以查出结果

db.testColl.find({"person":{"$elemMatch":{"ccc":{"$elemMatch":{"ccc3":56}}}}});

  

无法查出结果

db.testColl.find({"person":{"$elemMatch":{"ccc":{"ccc3":56,"fff3":78}}}});

db.testColl.find({"person":{"$elemMatch":{"ccc.ccc3":56}}});

  

可以查出结果
也就是说第二种方法不能嵌套使用。 

原文地址:https://www.cnblogs.com/wuxiang/p/5525835.html