首页 > 解决方案 > Mongodb array query: find records that contain an outsider in an array

问题描述

I have a database for my image tags with a web UI for labeling the tags. The tags are stored in documents with the following structure:

{
 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'}
]
}

I am looking for documents that contain incorrect tags, typo, in my example. I tried

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

and

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

This is not a duplicate of Find documents with array that doesn't contains a specific value as I am looking for a document containing an array that DOES contain the value in question while at the same time contains ANY OTHER value. The solutions presented in that question do not work in my situation as shown above.

标签: arraysmongodbmongodb-query

解决方案


You can use $elemMatch to specify the $ne part of your query:

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

推荐阅读