MongoDB:如何通过子文档ID查找? [英] MongoDB: How to find by subdocument ID?

查看:506
本文介绍了MongoDB:如何通过子文档ID查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对games的概念建模,其中playersteams在MongoDB中相互竞争.

I am trying to model the concept of games where teams of players compete against each other in MongoDB.

我有两个集合:playersgames.

这是games中的文档的外观.

{
    "_id": { "$oid": "1" },
    "teams": [
        {
            "players": [
                {
                    "player": { "$oid": "2" },
                    "score": 500,
                },
                {
                    "player": { "$oid": "3" },
                    "score": 550,
                }
            ]
        },
        {
            "players": [
                {
                    "player": { "$oid": "4" },
                    "score": 500,
                },
                {
                    "player": { "$oid": "5" },
                    "score": 550,
                }
            ]
        }
    ]
}

这是任务:给定玩家ID,我想找到该玩家参与的所有游戏.

Here's the task: given a player ID I want to find all games in which this player participated.

我尝试过的事情:

db.games.find( { "teams.players.player._id": "2" } )

但是,这不会返回任何内容.

However, this does not return anything.

顺便说一句,我使用的Mongoose具有以下架构:

By the way, I'm using Mongoose with the following schema:

playerSchema = Schema
    player: { type: Schema.ObjectId, ref: 'Player' }
    score: { type: Number }

teamSchema = Schema
    players: [ playerSchema ]

gameSchema = Schema
    teams: [ teamSchema ]

使用以下CoffeeScript查询:

with the following CoffeeScript query:

Game.find 'teams.players.player._id': playerId

对于任何玩家ID均不返回任何结果.

which returns no results for any player ID.

推荐答案

在您的文档中:

"players": [
            {
                "player": { "$oid": "4" },
                "score": 500,
            },
            {
                "player": { "$oid": "5" },
                "score": 550,
            }
        ]

players的嵌入式集合中的player字段是BSON ID(即,它看起来类似于ObjectId("4e208e070347a90001000008")),所以我认为您应该这样构造查询:

The player field in the embedded collection of players is a BSON Id (i.e. it looks something like ObjectId("4e208e070347a90001000008")), so I think you should structure your query like so:

db.games.find( { "teams.players.player": ObjectId("2") } )

注意,我已经删除了_id-只要它可以在mongo控制台中工作,那么我怀疑Coffee查询将是相似的(删除_id部分).

Note, I've dropped the _id -- provided that works in a mongo console, then I suspect the Coffee query will be similar (drop the _id portion).

这篇关于MongoDB:如何通过子文档ID查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆