MongoDB分离然后过滤

时间:2018-09-28 21:39:00

标签: mongodb aggregation-framework

假设我有一个藏书库

{"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出现在列表中。
我该怎么办?

1 个答案:

答案 0 :(得分:1)

去那里:

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”条目)。