Mongo query that requires matching on two arrays

时间:2016-08-31 18:52:46

标签: mongodb mongodb-query

I have the following collection in MongoDB 3.2.

db.collection.insert(
    {
        permissions: [
            {field: 'name', canEdit: true},
            {field: 'age', canEdit: false}
            // ... lots of other fields
        ],
        inputs: [
            {field: 'name', edited: false},
            {field: 'age', edited: false}
            // ... lots of other fields
        ]
    }
);

Is there a way to write a MongoDB query that returns all documents that have at least one field with both canEdit = true and edited = true?

The above question expressed in a pseudo manner:

find document D where exists
    P in D.permissions
    I in D.inputs
    P.field = I.field and P.canEdit = true and I.edited = true

1 个答案:

答案 0 :(得分:0)

您可以使用$elemMatch条件,因为collection本身就是

之类的数组
db.collection_name.find(
  { collection: { $elemMatch: { "permissions.canEdit": true, "inputs.edited": true } } })