代码之家  ›  专栏  ›  技术社区  ›  Mansa

仅当不在数组中时计数

  •  1
  • Mansa  · 技术社区  · 6 年前

    我有一组文档,其中有一个数组:

    {
      "_id": {
        "$oid": "5b602207a2f56b05028038c1"
      },
      "groupId": "5b32929cfc37de04f3ce9004",
      "updated": 20180731084703,
      "data": {
        "type": "WallStory",
        "playerId": "5b6003ca031f5bc44d59bb7b",
        "time": "0847",
        "story": "This is my new atory...",
        "reads": [
          "5b6003ca031f5bc44d59bb7b"
        ]
      }
    }
    

    现在,我要做的是计算“reads”数组中没有用户ID的所有文档。我不知道该如何完成?

    我在想这样的事情,但没有成功。

    var newStories = 0;
    newStories += dbCollection('groupWallStories').count({"groupId": "5b32929cfc37de04f3ce9004", "data.reads": thisUserId }).sort({"updated": -1}).limit(10);
    

    希望有人能引导我朝正确的方向前进,并提前感谢:—)

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ashh    6 年前

    count() $ne

    dbCollection('groupWallStories').count({ "data.reads": { "$ne": thisUserId } })
    

    $setIsSubset $cond

    db.collection.aggregate([
      { "$group": {
        "_id": null,
        "count": {
          "$sum": {
            "$cond": {
              "if": {
                "$setIsSubset": [
                  [ "5b6003ca031f5bc44d59bb7b" ],
                  "$data.reads"
                ]
              },
              "then": 1,
              "else": 0
            }
          }
        }
      }}
    ])
    

    id ObjectId