MongoDB。如何将文档从一个数组移动到另一个数组?

时间:2019-05-22 08:18:23

标签: node.js mongodb mongoose

我有一个Session集合。集合如下:

_id:ObjectId(5ce3c94f0e259e7370966c63)
status:Int32(1)
title:String(dfsb)
content:String(fdbfdbfd)
Array(visits):[
]
Array(visits_online):[
    0:Object
        start:Date(2019-05-22T08:06:50.222+00:00)
        _id:ObjectId(5ce5031ae8ee2e83b9ab23ff)
        session_id:ObjectId(5ce3c94f0e259e7370966c63)
        user_id:ObjectId(5ce4f290e2971cc6791e5a11)
        end:Date(2019-05-22T08:06:51.438+00:00)
    1:Object
        start:Date(2019-05-22T08:07:11.512+00:00)
        _id:ObjectId(5ce5032fe8ee2e83b9ab2403)
        session_id:ObjectId(5ce3c94f0e259e7370966c63)
        user_id:ObjectId(5ce4f290e2971cc6791e5a11)
        end:Date(2019-05-22T08:07:11.791+00:00)
]

我需要什么: 我想将子文档从visits_online数组移到visits数组

_id:ObjectId(5ce3c94f0e259e7370966c63)
status:Int32(1)
title:String(dfsb)
content:String(fdbfdbfd)
Array(visits):[
        0:Object
        start:Date(2019-05-22T08:06:50.222+00:00)
        _id:ObjectId(5ce5031ae8ee2e83b9ab23ff)
        session_id:ObjectId(5ce3c94f0e259e7370966c63)
        user_id:ObjectId(5ce4f290e2971cc6791e5a11)
        end:Date(2019-05-22T08:06:51.438+00:00)
]
Array(visits_online):[
    1:Object
        start:Date(2019-05-22T08:07:11.512+00:00)
        _id:ObjectId(5ce5032fe8ee2e83b9ab2403)
        session_id:ObjectId(5ce3c94f0e259e7370966c63)
        user_id:ObjectId(5ce4f290e2971cc6791e5a11)
        end:Date(2019-05-22T08:07:11.791+00:00)
]

我尝试做的事情:

Session.update({ _id: '5ce3c94f0e259e7370966c63', 'visits_online._id': mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') },
        {
            $pull: { 'visits_online._id': mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') },
            $push: { visits: mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') },
        })

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

mongo查询中有一个小错误,您需要告诉mongo从哪个数组中提取对象。

此外,您需要传递ObjectId而不是string才能与更新查询中的_id匹配。

当前,您将其作为_id : '5ce3c94f0e259e7370966c63'传递,但应为_id:_id: mongoose.Types.ObjectId('5ce3c94f0e259e7370966c63')

尝试一下:

Session.update({ 
    _id: mongoose.Types.ObjectId('5ce3c94f0e259e7370966c63'), 
    'visits_online._id': mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') 
},{
    $pull: { visits_online :  { _id: mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') }},
    $push: { visits: mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') },
})

有关更多信息,请阅读mongodb $pull documentation。希望对您有所帮助!