3

I am using Codeigniter with PHP. We can define empty array for mongodb query like following,

$db->user->insert(array('report'=> array()));

How i can define empty document(datatype) for mongodb in PHP?

Here i know, i can create the document variable when using another run time query (using $set or else). But i need to create document variable, when i insert.

If i create document variable like following,

$a = array();
$db->user->insert(array('report'=> $a));

following code is not working,

$db->user->update(
    array('user' => $user ), 
    array('$set' => array(
        'report.' . $number => 
             array('id'=>$number, 'on' => time(), 'status'=> 0)
    )));

here, $number is string variable.

10
  • Do you mean a field in your document called document? Commented Jan 3, 2013 at 8:47
  • 1
    @Sammaye document is a database field type in MongoDB Commented Jan 3, 2013 at 10:27
  • What happens if you pass along an empty array() as in your example? This should work and store an empty document. Commented Jan 3, 2013 at 10:30
  • @SaschaM78 It is? Have you got a page explaining a Document field type? Commented Jan 3, 2013 at 10:40
  • 1
    @SaschaM78 That: docs.mongodb.org/manual/reference/glossary/#term-bson-types is actually the list of types that BSON Documents support. Commented Jan 3, 2013 at 10:48

2 Answers 2

4

Finally no way for my question. I searched in many way. So, We can create the document variable when using another run time query (using $set or else). Thanks.

Sign up to request clarification or add additional context in comments.

Comments

0

The MongoDB PHP driver supports sending in empty objects (it has no validation on it's end to make sure you send something of value) to be saved but detecting that this method of saving objects would be useless without knowing the _id of the object you have just saved you can do:

$a = array();
$db->user->insert($a);
var_dump($a['_id']);

Since if passed a variable, the insert function for MongoDB will modify (by reference) the original variable and add the _id field to it.

You cannot save a "empty" object however (an object without the immutable _id) to a normal collection. This of course differs for things like capped collections.

2 Comments

So What? What you meant by brackets?
@KarSho Yea so where you see 3 brackets on the last line of your edit there is only supposed to be two. Can you show us an example doc of what your updating and and can you tell us what $user is? Are you sure this actually finds a doc?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.