从使用对象转换为数组后,如何转换MongoDB查找操作

时间:2014-10-31 05:07:54

标签: mongodb

我将MongoDB子文档从对象更改为数组。

这是最初的样子。

"transactions": {
    "TX1234": {
        "guid": "TX1234",
        "amount": 102,
        "email_sent": false
    },
    "TX1235": {
        "guid": "TX1235",
        "amount": 102,
        "email_sent": true
    }
}

我曾经使用过这种程序化查找操作。

var email_sent_lookup = {};
email_sent_lookup['transactions.' + transaction_guid + '.email_sent'] = true;
if(Donate.findOne(email_sent_lookup)){
    return true;
}

如何将其转换为查找数组内部(现在如下所示)?

transactions: [
    {
        "guid": "TX1234",
        "amount": 102,
        "email_sent": false
    },
    {
        "guid": "TX1235",
        "amount": 102,
        "email_sent": true
    }
]

1 个答案:

答案 0 :(得分:1)

您需要使用$elemMatch

e.g:

MyCollection.findOne({ 
    transactions: { 
        $elemMatch : {
           email_sent: { $eq: true },
        }
    }
});

或简写:

MyCollection.findOne({ 
    transactions: { 
        $elemMatch : { 
            guid: 'TX1234',    // find the GUID
            email_sent: true   // did you send it? DID YOU SEND IT?!?
        }
    }
});