Find documents where ALL elements of an array have a specific value

元气小坏坏 提交于 2019-12-23 23:49:34

问题


This is basically a simple problem, but I couldn't find a query function for it.

Example Collection:

{
  _id: 1,
  foo: [
    { bar: 9 },
    { bar: 16 }
  ]
}

{
  _id: 2,
  foo: [
    { bar: 9 },
    { bar: 9 },
    { bar: 9 }
  ]
}

Example Output:

{
  _id: 2,
  foo: [
    { bar: 9 },
    { bar: 9 },
    { bar: 9 }
  ]
}

Because this is the only document where every foo.bar = 9.

The Query I'm looking for:

"FIND all documents WHERE foo.bar = 9 FOR EVERY foo.bar in this document."

Or do I need something like "FIND all documents WHERE NOT( foo.bar != 9 )"?

Thank you in advance!


回答1:


db.c.find({
    "foo.bar" : {
        $exists : true
    },
    "foo" : {
        $not : {
            $elemMatch : {
                "bar" : {
                    $ne : 9
                }
            }
        }
    }
});


来源:https://stackoverflow.com/questions/26392534/find-documents-where-all-elements-of-an-array-have-a-specific-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!