【问题标题】:Use of $nin on embedded document在嵌入文档上使用 $nin
【发布时间】:2016-10-25 20:15:11
【问题描述】:

我在 MongoDB 中有这样的架构:

var Customers = new Schema({
    name: { type: String, trim: true, index: true, default: null, sparse: true },
    facebookId: { type: String, default: null, trim: true, index: true },
    friends: [friends]
});

var friends = new Schema({
    customer: { type: Schema.ObjectId, ref: 'Customers', required: true },
    lastGame: { type: Schema.ObjectId, ref: 'games', required: true, default: null },
    lastGameTime: { type: Date, default: null }
});

现在在 friends 数组中,我有所有客户的参考,他们是特定客户的 Facebook 朋友。

现在我想做的是我有一个屏幕,我想在其中显示所有客户,但我不希望那些已经是我的 Facebook 朋友的客户,例如,假设我有 10客户总数从 1 到 10,我是 客户编号 4,在朋友数组中有 客户 1,3,5,6 > 所以我在屏幕上的结果应该是用户 2,7,8,9,10

如果有人能通过使用 MongoDb 的 Query 告诉我获得这些东西的方法,我将非常感激。我已经搜索并找到了 $nin 用法,但这适用于简单数组。我不明白如何在嵌入式文档上实现这个查询,就像我的情况一样。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    查看 $elemMatch。这将允许您识别嵌入文档数组中的特定文档

    ElemMatch MongoDB documentation

    您也可以将 $elemMatch 与 $nin 结合使用

    【讨论】:

      【解决方案2】:

      我通过使用 $nin 以一种简单的方法解决了这个问题首先我在一个数组中选择特定客户的所有朋友,然后使用 $nin 我从查询中过滤掉所有朋友,得到我的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-22
        • 1970-01-01
        相关资源
        最近更新 更多