0

I build a string,containing mongodb queries using PHP. How can i execute that Query.For example, lets consider my string as

$x = array(
    'tag_id'=>'$value',
    'content_id'=>'$content_id',
    'createdby'=>'test',
    'created_date'=>date('d-m-Y'))

Now this is the query which i want to execute. If i give this string like this mongocollection->insert($x), Its saying , mongodb exception, with no documents given. So how can i convert this string into executable statement

Roberto Reale
  • 4,247
  • 1
  • 17
  • 21
Matchendran
  • 333
  • 2
  • 6
  • 20
  • Why are you building a string as opposed to just using native code? – Neil Lunn Apr 18 '14 at 09:52
  • @NeilLunn:iam building query which contains many documents. Each document differ by the value of `'KEY: tag_id'`, i am getting those tag_id values from one array. So only i am building a query. Something like this `"array( 'tag_id'=>'$value', 'content_id'=>'$content_id', 'createdby'=>'test', 'created_date'=>date('d-m-Y')), array( 'tag_id'=>'$value1', 'content_id'=>'$content_id', 'createdby'=>'test', 'created_date'=>date('d-m-Y')), array( 'tag_id'=>'$value2', 'content_id'=>'$content_id', 'createdby'=>'test', 'created_date'=>date('d-m-Y'))"` – Matchendran Apr 18 '14 at 10:08
  • 1
    So still, why are you not using native code? It's code, not hardcoding. This is not SQL, so you can actually dynamically build data structures using push etc. – Neil Lunn Apr 18 '14 at 10:11
  • If i use push, mutiple inserts statements have to be compiled(forgive my ignorance ,if i am wrong),instead i am using `batchInsert` statement, single time, query will be compiled. – Matchendran Apr 18 '14 at 10:46
  • Not mongo $push. I'm talking about building your data structure (which is what a query is) in code. Something I [**posted**](http://stackoverflow.com/questions/22198172/generating-a-structure-for-aggregation) a while ago might serve as a better example for you to look at. – Neil Lunn Apr 18 '14 at 10:52
  • Did that actually clarify things for you? I just was not sure you were understanding the difference of working in a native dynamic language form as opposed to "constructing queries" in something like SQL. – Neil Lunn Apr 18 '14 at 12:16
  • @NeilLunn: No neil. I dont have any knowledge about working in native dynamic language form. – Matchendran Apr 19 '14 at 05:57

1 Answers1

0

Try this:

$m = new MongoClient();
//Your collection name
$collection = $m->selectDB("foo")->selectCollection("bar");

$x = array(
    'tag_id'=>'$value',
    'content_id'=>'$content_id',
    'createdby'=>'test',
    'created_date'=>new MongoDate('d-m-Y'));

$collection->insert($x);
DShah
  • 472
  • 5
  • 15