我在数据库中有一个用户文档。
users: [
{
id: 3435,
userName: "User name",
books: [
{
id: 5453,
bookId: 123,
name: "Book name",
authors: [{
country: "USA"
name: "Author name"
}]}
]
}
]
如果图书不存在,我需要做的是将新书数据插入到图书数组中。但如果存在,我想更新特定书籍的书籍数据。
我如何在mongo 中实现这一点
如果不存在,那么执行此操作以更新或插入
db.posts.update({book: [array you want to update]},
{New Array},
{upsert: true},
)
使用$exist验证字段是否存在,如果字段不存在,则使用upsert=true插入。
mongo查询格式如下!db.collection.update(query, update, options)
答案是
db.getCollection('user').update(
{
books: {$exists: true},
id: '54'
},
{
$set:
books:[
{
id: 5453,
bookId: 123,
name: "Book name",
authors: [{
country: "USA"
name: "Author name"
}]}
]
},
upsert=True
)