Verify if a document is present within the collection; if not, insert a new document

I am currently using PHP and MongoDB to save songs that users add through a basic form. The structure of the collection I have created is as follows.

$object = array(
    "trackName" => "Sju sorger",
    "artistName" => "Veronica Maggio",
    "albumName" => "Satan i Gatan",
     );
$collection->save($object);

My goal is to check whether a song already exists in the collection. If the user is attempting to add a song that is not already in the collection, it will be added. However, if the song is already present, a message indicating that the song is already in the collection will be displayed.

As someone who is new to MongoDB, I believe I can achieve this by checking the _id of the document. Nevertheless, I am unsure of how to go about doing so.

Any assistance on this matter would be greatly appreciated.

Answer №1

Try out this method.

  <?php
    try {
      // establish a connection with the MongoDB server
      $conn = new Mongo('localhost');

      // access the database
      $db = $conn->test;

      // access the collection
      $collection = $db->items;

      // FETCH TRACK NAME
      $trackname = 'placetracknamehereifsearchingbytrackname';
      // retrieve an existing document
      $criteria = array(
        'trackName' => trackname ,
      );
      $doc = $collection->findOne($criteria);

      if(!empty($doc) {
         echo 'Data Already Exist';
      } else {
  // insert a new document
  $object = array(
    "trackName" => "Sju sorger",
    "artistName" => "Veronica Maggio",
    "albumName" => "Satan i Gatan",
     );
     $collection->save($object);
     echo 'Added Successfully!';
}
      // disconnect from the server
      $conn->close();
    } catch (MongoConnectionException $e) {
      die('Error connecting to MongoDB server');
    } catch (MongoException $e) {
      die('Error: ' . $e->getMessage());
    }
    ?>

refer to this source for more information.

Mongo Resource

Answer №2

Currently, the most effective approach is to utilize the upsert option within the update operation in MongoDB. This feature allows for either inserting or updating data and ensures atomicity - a quality lacking in the example provided. To determine whether the document has been replaced, one can monitor the nUpserted value of the WriteResult

For more information, please visit:

https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-option

https://docs.mongodb.com/manual/reference/method/WriteResult/#WriteResult.nUpserted

Despite its age, this question continues to appear in search results and has been referenced in previous discussions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Laravel : How to utilize Eloquent to perform joins within a query

Within my database, I am working with five tables where I need to extract data from all of them: post, product, categories, attributes, post_attribute Currently, I have a query in my model that retrieves all posts for a particular product, including detai ...

Using Ajax (Jquery) to send data to a PHP script

Currently, I am working on an application where users can click a checkmark to complete a task. When this action is taken, a popup window appears (created using bootstrap), prompting the user to enter their hours worked on the task. After entering the hour ...

Issue with call function not operating consistently across all subclasses

I am experimenting with using the __call function for pre-action instructions. The issue I am facing is that the __call function only works once, but I need it to be triggered every time the run() method is called. When I call $second_child->run() ins ...

Error: Unexpected curly bracket found, expecting a comma or semicolon instead issue

Struggling to identify the bug in my code. Could really use some assistance. <?php if(isset($_SESSION["pkg_error"])); ?> <div class="error_msg_cont"> <?php foreach($_SESSION["pkg_error"] as $error) { echo $error. "&l ...

Obtaining additional information through ajax in Yii2

I have encountered an issue where, while receiving data from an ajax call, I am also getting unnecessary data such as all the contents of my PHP files. The problem is illustrated in the image below. How can I resolve this issue? https://i.stack.imgur.com ...

What is the best way to manage a session using JavaScript?

Currently developing a website that initially hides all elements except for the password box upon loading. Once the user enters the correct password, all webpage elements are revealed. Seeking a solution to keep the elements visible on reload by utilizing ...

How can one obtain a distinct identifier retroactively?

One thing that I am working on is changing button images upon clicking, but this isn't the main issue at hand. Each button corresponds to unique information retrieved from the database, and when clicked, the button should change and send the appropria ...

After performing a URL rewrite, the Yii Ajax save operation returns a 301 response

I've implemented an inline editor that utilizes AJAX to save content by calling a Yii controller. The process works perfectly fine. However, after shortening my URLs using .htaccess and Yii urlManager, I encountered a 301 response when trying to save ...

Managing versions of code with TortoiseSVN

Currently getting to know how subversion control functions. Attempting a PHP project on my local server and desiring to collaborate with someone from a different system so they can also contribute changes to the project. Thinking about using TortoiseSVN ...

Create a personalized edit button for ContentTools with a unique design

I'm struggling to figure out how to customize the appearance and location of the edit button in ContentTools, a wysiwyg editor. After some research, I learned that I can use editor.start(); and editor.stop(); to trigger page editing. However, I want ...

Emphasize hyperlink according to the current page (Dynamic Navigation using PHP)

While some may find this task simple, I have been struggling to make it work despite trying various methods. Let me give you a brief overview; I have a single page with links that, when clicked, load other pages but display them within the same page. ...

Is it possible to use combox to deactivate the buttons?

My goal is to deactivate the button as soon as I select a value from the drop-down list. For example, here's what I have: <select name =""> <option> disable </option> <option> enable </option> </select> <input ...

How to enhance a jQuery tab control by implementing custom JavaScript forward and back arrows?

Although there are other questions related to this topic, mine is unique. I have a scrolling jQuery feature that utilizes tabs for selection and is automated. Modifying the layout is challenging because it is dynamic and depends on the number of items in t ...

"Make sure to specify Safari input field as an email and mark

I am experiencing an issue with a contact form in my HTML/PHP code. Everything seems to be working fine, but when using the SAFARI browser, the form fails to validate if I try to submit without filling out all input fields. For example, my form includes: ...

Retrieve external/parent page

This might be a little confusing, but here's what I've been working on. On my website, I have a main page that uses JQuery.load() to load a secondary php page. The main page's URL is: localhost/piproject/roster.php?id=2 However, when I try ...

Combining SELECT queries for merging similar results in a non-DISTINCT result set

---------- ---------- ---------- ---------- | t1 | | t2 | | t3 | | t4 | ---------- ---------- ---------- ---------- | id | | id | | id | | t1_id | | foo | | bar | | foobar | | t2_id ...

Wrangler of RESTful services with mongoDB, I am currently grappling with the challenge of converting BSON values to JSON

I'm currently utilizing cowboy for RESTful services with mongoDB. I encountered an error related to BSON value to JSON conversion (specifically '_id' in mongodb value). Does anyone have any ideas on how to retrieve mongoDB documents, convert ...

The Ajax confirmation prompt seeks a singular piece of information

After implementing an ajax beforeSend function with a confirm() statement, I encountered a problem. The issue is that when attempting to delete the first value, it correctly prompts for confirmation. However, if trying to delete the second, third, or fourt ...

Challenges with Wordpress themes

Currently working on developing a Wordpress Theme, nothing too special. Ran into an issue the other day. The problem is as follows: when I insert the below code into header.php <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory& ...

Strategies for optimizing polling of mySQL database using $http.get

** ANGULAR 1.X ** Hey there! I'm currently seeking assistance in making this $http.get function asynchronous. Currently, my workaround involves using a setInterval on the displayData scope. However, this solution is not efficient as it consumes a lot ...