【问题标题】:Can MongoDB create friend relationship with one query?MongoDB可以通过一个查询创建朋友关系吗?
【发布时间】:2017-07-01 19:49:05
【问题描述】:

我正在为朋友关系编写一些 mongoDB 查询。假设有一个如下所示的用户文档:

User:
{
    _id: 1
    Friends: [2,3,8] // an array of identifier
}

如果我想写两个用户成为朋友的查询,我需要写两个查询:

  db.Users.update({_id: x}, {$push: {Friends: y}});

  db.Users.update({_id: y}, {$push: {Friends: x}});

我的问题是:我可以将以上两个结合到一个查询中吗?如果有,怎么写?

【问题讨论】:

    标签: mongodb database nosql


    【解决方案1】:

    实际上你不能。 因为MongoDB不支持这样的功能,你只能写两个查询来达到你的目的。

    【讨论】:

      【解决方案2】:

      afaik,你不能在一次更新中做到这一点,但你应该对批量更新感兴趣:http://docs.mongodb.org/manual/reference/method/Bulk/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多