top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Search in Mongodb using PHP?

+3 votes
314 views

I am very new to mongodb, my requirement is need to search a value in two fields. ex: first_name, last_name

I am using PHP as serverside and mongodb as backend.

Can you please suggest, How can I write the query in PHP.

Below is the things, I tried to implement but not succeeded.

db.users.aggregate(
  [
  { $project: { userName: { $concat: [ "$first_name", " - ", "$last_name" ] } } }
  ]
)
posted Dec 21, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

You probably don't want to use an aggregate here but if you do you'll want to use a $match clause to search two fields. You query above will return all rows concatenating the two names fields you mention.
Example : insert these data

db.users.insert ( { first_name: "Salil", last_name: "Kumar Agrawal" } );
db.users.insert ( { first_name: "Shivam", last_name: "Kumar Pandey" } );

Using a standard find...

 db.users.find( { first_name: "Shivam", last_name: "Kumar Pandey" } );

Returns...

{
 "_id" : ObjectId("567902a425d93f0f90c5bc9c"),
 "first_name" : "Shivam",
 "last_name" : "Kumar Pandeyl"
}

Using aggregate...

db.users.aggregate([ { "$match": { first_name: "Shivam", last_name: "Kumar Pandeyl" } } ]);

Returns...

{
 "_id" : ObjectId("567902a425d93f0f90c5bc9c"),
 "first_name" : "Shivam",
 "last_name" : "Kumar Pandeyl"
}

Your aggregate query returns the following...

{ "_id" : ObjectId("567902a425d93f0f90c5bc9c"), "userName" : "Salil - Kumar Agrawal" }
{ "_id" : ObjectId("567902b325d93f0f90c5bc9d"), "userName" : "Shivam - Kumar Pandey" }
answer Apr 30, 2016 by Shivam Kumar Pandey
Similar Questions
+1 vote

I recently upgraded the latest PHP driver and could do an "explain" query by using the "$explain" modifier when executing the query, however as of MongoDB 3.2 the operator was removed so this is no longer possible.

So my question is how can I do an explain query with the new driver and MongoDB 3.2?

+2 votes

I am new to mongodb but I know php so I want to implement both and develop a single page application using php and mongoDB.A sample code will be helpful for me like.CRUD Operation

+1 vote

I am using mongo db version 2.2.3 . I am having the requirement like user gives the input like "(ash|ben) & (Bus|car)" as search keywords. In this the & is for AND condition and | for the OR condition.
Is there any way to make this nested leywords as a mongodb query in node js. Is there any functionality in mongodb to achieve this?. If not how can make this in any other way?

+1 vote

I am able to run the web application using php and mongodb 3.2.6 in localhost.But I need to deploy mongodb in existed servers like Hostgator or Godaddy, then I need to run the php(5.4) web application.

Is it possible? Please suggest me to run my php application to connect mongodb?

...