MongoDb $ elemMatch未按预期工作

时间:2017-11-30 15:49:46

标签: mongodb

我正在编写一个简单的查询,使用符合Tags的对象,如果以下情况属实,则必须返回文档:

  1. 它有3个项目
  2. 其中一个是:image
  3. 其中一个以:开头,但不是图片
  4. 其中一个人不以:
  5. 开头

    所以我想要{ Tags : [":image", ":ianything", "somethingelse"] }

    类型的记录

    我写下以下内容:

    db.myCollection.find({
      Tags: {
        $elemMatch: {
          $eq: ":image"
        },
        $elemMatch: {
          $ne: ":image",
          $regex: /^:\w+$/
        },
        $elemMatch: {
          $regex: /^\w+$/
        },
        $size: 3
      }
    }).limit(50)
    

    但它没有按预期工作并返回{ Tags : [":image", "something", "somethingelse"] }

    等项目

    我错在哪里?

1 个答案:

答案 0 :(得分:1)

您需要使用$and来组合条件:

db.myCollection.find({ $and: [
  { Tags: {
    $elemMatch: {
      $eq: ":image"
  } } },
  { Tags: {
    $elemMatch: {
      $ne: ":image",
      $regex: /^:\w+$/
  } } },
  { Tags: {
    $elemMatch: {
      $regex: /^\w+$/
  } } },
  { Tags: { $size: 3 } }
] });