MongoDB:如何通过子文档ID查找?

编程入门 行业动态 更新时间:2024-10-17 19:24:11
本文介绍了MongoDB:如何通过子文档ID查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

我有两个集合:players和games.

这是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查找?

本文发布于:2023-11-22 13:36:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617625.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   MongoDB   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!