首页 > 解决方案 > MongoDB 区分然后过滤

问题描述

假设我有一个藏书:

{"name": "Mongodb", "authors": [{"name": "John"}, {"name": "Peter"}, {"name": "Joe"}]}  
{"name": "MySQL", "authors": [{"name": "John"}, {"name": "Alice"}, {"name": "Kate"}]}
{"name": "SQL Server", "authors": [{"name": "John"}, {"name": "Steve"}]}

我想找到与John.

当我使用查询时:db.book.distinct('authors.name', {'authors.name': 'John'})

它将返回以下结果:[John, Peter, Joe, Alice, Kate, Steve]

但是,我不想John在列表中。
我怎样才能做到这一点?

标签: mongodbaggregation-framework

解决方案


你去:

db.book.aggregate({
    $match: {
        "authors.name": "John" // only look at documents that contain "John" in the list of authors (this part could use an index on "authors.name")
    }
}, {
    $unwind: "$authors" // flatten the authors array into separate documents
}, {
    $group: {
        _id: null, // throw all documents in the same bucket
        authors: { $addToSet: "$authors.name" } // add all authors' names into an array called "authors" eliminating duplicate entries
    }
}, {
    $project: {
        "co-authors": {
            $filter: { // remove "John" from the list of entries
                "input": "$authors",
                "as": "this",
                "cond": { $ne: [ "$$this", "John" ] }
            }
        }
    }
})

但是,我认为您当前的“解决方案”更加优雅。它所缺少的只是一点点客户端过滤(从返回的条目列表中删除“John”条目)。


推荐阅读