【问题标题】:MongoDB query into an array of arraysMongoDB查询到数组数组
【发布时间】:2016-04-18 12:35:19
【问题描述】:

我的数据库中有以下架构:

{ name: 'AFG',
  documents: [
    { name: 'doc1',
      templates: [
        { name: 'templ1',
          lastModified: <Date>},
        ...]
    },
    ...]
}

我正在尝试进行查询以查找名称为“templ1”的模板。如果我找到它,我必须将上次修改日期与另一个日期进行比较并更新值。如果找不到,我只好把它推入数组中。

我已尝试使用以下查询来做到这一点:

Country.findOne({name : countrySelected, documents : {$elemMatch: {name: documentSelected}}, 'documents.templates' : {$elemMatch: {name: templateSelected}}}, function(err, templateFound){...}

但我收到以下错误:

MongoError: cannot use the part (documents of documents.templates) to traverse the element ({documents: [ { name: "Passport", templates: [] }, { name: "Visa", templates: [] }, { name: "Driver's Licence", templates: [] }, { name: "Id Card", templates: [] }, { name: "Other", templates: [] } ]})

有人知道我该怎么做吗?谢谢!!

【问题讨论】:

标签: arrays node.js mongodb mongodb-query mongojs


【解决方案1】:

您必须使用$in 运算符在数组中搜索。

Country.findOne({
    name : countrySelected, 
    documents: {
        $elemMatch: {
            $and: [{
                name: {
                    $in: documentSelected //<-- must be array like ['doc1']
                }
            }, {
                'templates.name': {
                    $in: documentSelected //<-- must be array like ['tmpl1']
                 }
            }]
        }
    }
}, function(err, templateFound){
    //do something with err and templateFound
});

要更新 LastModified 日期,您需要在回调函数中更新它并保存文档。

See this answer for nested array updates

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2013-06-22
    • 2014-05-21
    • 2021-09-24
    相关资源
    最近更新 更多