【发布时间】:2014-06-09 09:10:50
【问题描述】:
我刚开始使用 MongoDB,对如何更新数据库中的文档有一些疑问。我在我的数据库中插入两个文档
db.userscores.insert({name: 'John Doe', email: 'john.doe@mail.com', levels : [{level: 1, hiscores: [90, 40, 25], achivements: ['capture the flag', 'it can only be one', 'apple collector', 'level complete']}, {level: 2, hiscores: [30, 25], achivements: ['level complete']}, {level: 3, hiscores: [], achivements: []}]});
db.userscores.insert({name: 'Jane Doe', email: 'jane.doe@mail.com', levels : [{level: 1, hiscores: [150, 90], achivements: ['Master of the universe', 'capture the flag', 'it can only be one', 'apple collector', 'level complete']}]});
我检查我的插入是否与 find() 命令一起工作,看起来没问题。
db.userscores.find().pretty();
{
"_id" : ObjectId("5358b47ab826096525d0ec98"),
"name" : "John Doe",
"email" : "john.doe@mail.com",
"levels" : [
{
"level" : 1,
"hiscores" : [
90,
40,
25
],
"achivements" : [
"capture the flag",
"it can only be one",
"apple collector",
"level complete"
]
},
{
"level" : 2,
"hiscores" : [
30,
25
],
"achivements" : [
"level complete"
]
},
{
"level" : 3,
"hiscores" : [ ],
"achivements" : [ ]
}
]
}
{
"_id" : ObjectId("5358b47ab826096525d0ec99"),
"name" : "Jane Doe",
"email" : "jane.doe@mail.com",
"levels" : [
{
"level" : 1,
"hiscores" : [
150,
90
],
"achivements" : [
"Master of the universe",
"capture the flag",
"it can only be one",
"apple collector",
"level complete"
]
}
]
}
如何向我的用户分数添加/更新数据?假设我想在级别 1 上向用户 John Doe 添加一个 hiscore。如何插入 hiscore 75 并且仍然对 hiscore 数组进行排序?我可以限制 hiscores 的数量,使数组只包含 3 个元素吗?我试过了
db.userscores.aggregate(
// Initial document match (uses name, if a suitable one is available)
{ $match: {
name : 'John Doe'
}},
// Expand the levels array into a stream of documents
{ $unwind: '$levels' },
// Filter to 'level 1' scores
{ $match: {
'levels.level': 1
}},
// Add score 75 with cap/limit of 3 elements
{ $push: {
'levels.hiscore':{$each [75], $slice:-3}
}}
);
但它不起作用,我得到的错误是“SyntaxError: Unexpected token [”。
另外,例如,我如何从 1 级的所有用户中获得 10 的最高分?我的文档方案是否可以,或者我可以使用更好的方案来为我的游戏存储用户在不同级别上的分数和成就?使用上述方案在查询或性能方面有什么缺点吗?
【问题讨论】:
标签: mongodb mongodb-query