【问题标题】:Mongodb array query: find records that contain an outsider in an array [duplicate]Mongodb数组查询:查找数组中包含局外人的记录[重复]
【发布时间】:2019-07-30 20:25:27
【问题描述】:

我有一个用于我的图像标签的数据库,带有一个用于标记标签的 Web UI。标签存储在具有以下结构的文档中:

{
 imgID: 'UID of corresponding image',
 tagID: 'UID of tag',
 coordinates:{x1,y1,x2,y2},
 tags:[
    {tag:'a', user:'username'},
    {tag:'a', user:'username'},
    {tag:'typo', user:'username'}
]
}

在我的示例中,我正在寻找包含错误标签 typo 的文档。 我试过了

find({$and:[{'tags.tag':{$ne:'a'}},{'tags.tag':'a'}]}),

aggregate([{
    $match:{'tags.tag':'a'}
},{
    $match:{'tags.tag':{$ne:'a'}}
}])`

这不是 Find documents with array that doesn't contains a specific value 的副本,因为我正在寻找一个包含数组的文档,该数组确实包含相关值,同时包含任何其他值。如上所示,该问题中提出的解决方案不适用于我的情况。

【问题讨论】:

    标签: arrays mongodb mongodb-query


    【解决方案1】:

    您可以使用$elemMatch 指定查询的$ne 部分:

    db.col.find({ $and:[ {'tags.tag': 'a' }, { tags: { $elemMatch: { 'tag': { $ne: 'a' } } } } ] })
    

    【讨论】:

      【解决方案2】:

      你必须使用 $elematch 来匹配数组的元素

      db.col.find({ $and:[ {'tags.tag': 'a' }, { tags: { $elemMatch: { 'tag': { $ne: 'a' } } } ] })

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多