繁体   English   中英

MONGODB 在文档集合中查找

[英]MONGODB find inside a document collection

我是 mongodb 的新手,所以我在这里遇到了一个小问题

我有一个看起来像这样的集合..

[
  {
    "_id": "5f7a1b6a3aedab1df33574bb",
    "name": "myFirstGame",
    "players": [
      {
        "_id": "5f7a1be79acaf41e058ccd9f",
        "name": "Albert",
        "points": 10
      },
      {
        "_id": "5f7a20de87f0fc1ea309145c",
        "name": "Adam",
        "points": 10
      },
      {
        "_id": "5f7a25fdcd01211fc84afd0e",
        "name": "John",
        "points": 10
      }
    ],
    "description": "This is a fun game to watch",
    "__v": 0
  }
]

我试图让那些名字是“约翰”的球员

所以,我实际上在做的是:

try{
        const cond = {
          _id: '5f7a1b6a3aedab1df33574bb', //the id of the game
          'players.name': { $eq: 'John' }, // the condition on the player
        }
        player = await Game.find(cond, 'players');
        return player;
}catch (e) {
    console.error(e);
}

我期望得到的是这样的对象

      {
        "_id": "5f7a25fdcd01211fc84afd0e",
        "name": "John",
        "points": 10
      }

但我得到了游戏的完整对象,没有任何过滤器

          'players.name': { $eq: 'John' }, // the condition on the player

在这个领域,我已经尝试过类似的东西

players: {name: 'John'} // this returns me an empty array
players.name: 'John'

我可以用 NodeJS 做这个过滤,但我认为这可能是用 mongo 解决这个问题的一种方法,

我对吗?

您的变量cond将游戏的 _id ( _id: '5f7a1b6a3aedab1df33574bb' ) 作为参数传递给Game.find() ,这就是它返回整个游戏的原因。

您是否尝试过直接查询,例如: db.Games.find( { name: "John" } )player = await Game.find({name: "John"}); ?

聚合发挥作用。

  1. $filter有助于在数组中查找特定对象
  2. $unwind使数组变平
  3. $replaceRoot将对象替换为根

蒙戈脚本

[
  {
    $project: {
      players: {
        $filter: {
          input: "$players",
          cond: {
            $eq: [
              "$$this.name",
              "John"
            ]
          }
        }
      }
    }
  },
  {
    $unwind: "$players"
  },
  {
    "$replaceRoot": {
      "newRoot": "$players"
    }
  }
]

工作Mongo 游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM