Reputation: 19
I have an user document in database.
users: [
{
id: 3435,
userName: "User name",
books: [
{
id: 5453,
bookId: 123,
name: "Book name",
authors: [{
country: "USA"
name: "Author name"
}]}
]
}
]
what i need to do is insert new book data to books array if the book is not exist. but if exist i want to update the book data of that specific book.
How I can achive this in mongo
Upvotes: 0
Views: 32
Reputation: 116
Use $exist to verify if the field exists and use upsert=true to insert if the field is not exist.
mongo query format like below!
db.collection.update(query, update, options)
Answer is ..
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
)
Upvotes: 0
Reputation: 72
Alright do this to update or insert if it's not there
db.posts.update({book: [array you want to update]},
{New Array},
{upsert: true},
)
Upvotes: 1