我有以下 mongo 檔案(非常簡單):
[
{
"_id": ObjectId("609c2c2d420a73728827e87f"),
"timestamp": "2021-01-01 12:00:00",
userId: 1,
"users": []
}
]
我想要實作的是:在更新檔案時,我想向用戶陣列添加(推送)一個用戶名。但是當陣列達到 5 個用戶名時,我想從串列中彈出第一個并添加一個新的。因此,串列中最多應包含 5 個用戶名。
我正在嘗試這樣做,但是這不起作用。到目前為止,這是我的查詢(帶有聚合管道):
db.collection.update({
"userId": 1
},
[
{
$set: {
timestamp: "2021-01-01 14:00:00"
}
},
{
$cond: {
if: {
"users.4": {
$exists: true
}
},
then: {
$pop: {
users: -1
}
},
else: "$users"
}
},
{
$push: {
"users": "my_username"
}
}
])
我是 mongodb 的初學者,我正在使用 node.js mongoose。
提前致謝!
uj5u.com熱心網友回復:
代替
{ $push: { "users": "my_username" } }
經過
{ $set: { users: { $concatArrays: [ "$users", ["my_username"] ] } } }
您正在使用聚合管道,但$push是更新運算子
出于同樣的原因,請使用$slice而不是$pop
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/396459.html
標籤:MongoDB
