1

Note: checking if the key books exist or not, creating if not and than updating it.

I am using mongodb driver with nodejs.

In the db.collection('userData')The document looks like this:

{ 
    user_id: 'user1',
    books: [{
               id: 'book1',
               title: 'this is book1'
    },
            {
               id: 'book1',
               title: 'this is book1'
    }]
}

when inserting a new book entry, how to check if the array of books exists in the document, if not then add a key books in the document and then insert the book entry.

turivishal
  • 34,368
  • 7
  • 36
  • 59
Squiba
  • 57
  • 6
  • i have to check if the key 'books' exist or not ? – Squiba Apr 23 '21 at 09:50
  • this is different, https://stackoverflow.com/questions/14527980/can-you-specify-a-key-for-addtoset-in-mongo , – Squiba Apr 23 '21 at 09:53
  • https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ ```db.scores.find( { results: { $elemMatch: { $gte: 80, $lt: 85 } } } )``` searches in array of elements. Maybe works with upsert command too? – huseyin tugrul buyukisik Apr 23 '21 at 10:03

1 Answers1

1

You have to do 2 separate queries,

  • Find user document
  • Check condition if books field present
  • If Present then push object, else set new field
var user_id = "user1";
var bookData = { id: 'book1', title: 'this is book1' };

// FIND USER DATA
var userData = await db.collection('userData').findOne({ user_id: user_id }, { books: 1 });

var updateBody = { $push: { books: bookData } };
// IF BOOKS FIELD NOT PRESENT THEN SET NEW
if (!userData.books) {
  updateBody = { $set: { books: [bookData] } };
}

var updateData = await db.collection('userData').updateOne({ user_id: user_id }, updateBody);

console.log(updateData);

Second option you can use update with aggregation pipeline starting from MongoDB 4.2,

  • $ifNull check is field is null then return []
  • $concatArrays to concat current books with new book object
var bookData = { id: 'book1', title: 'this is book1' };
db.collection('userData').update({
    // put your condition
  },
  [{
    $set: {
      books: {
        $concatArrays: [
          { $ifNull: ["$books", []] },
          [bookData]
        ]
      }
    }
  }],
  { multi: true }
);

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59