How to store object in Mongo DB as value? - php

Now, when I add values to Mongodb using PHP it stores as array:
{ "_id" : ObjectId("591e9b60470e6c500f3c9869"),"value" : [ "mama", "papa" ] }
How to store data for value as object: {"mama" : 1, "papa" : 2}?
I tried:
$data = array("value" => array("mama" => 1, "papa" => 2))
$this->collection->insert($data);
It is inserted as array!

Try using these lines -
$data = (object) ["value" => (object) ["mama" => 1, "papa" => 2]]
$this->collection->insert($data);
It'll create object with mentioned properties.

db.products.insert(
[
{ _id: 11, item: "pencil", qty: 50, type: "no.2" },
{ item: "pen", qty: 20 },
{ item: "eraser", qty: 25 }
]
)
or
{
"_id" : ObjectId("591c382a82956dc8a500002e"),
"name" : "alpesh",
"email" : "admin#gmail.com",
"contact_number" : "0123456789",
"position" : "devloper",
"updated_at" : ISODate("2017-05-17T11:46:50.000Z"),
"created_at" : ISODate("2017-05-17T11:46:50.000Z")
}

Related

Insert array in array at mongodb with php

MongoDB schema:
{
"_id" : ObjectId("60057ff5c34000008a00214a"),
"Name" : "Test Store",
"AFM" : "099360666",
"DOY" : "ffa",
"Address" : "faf",
"TEL" : "sss",
"Products" : [
{
"_id" : ObjectId("600584b8c34000008a00214d"),
"pID" : "099360666/1",
"pNAME" : "old scholl 2",
"pPRICE" : "55",
"pBRAND" : "vans",
"pDESCRIPTION" : "eco frinedly",
"pSIZE" : "45,44",
"pDEPARTMENT" : "Men/Shoes/Trainers",
"pTHUMBNAIL" : "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg",
"pQUANTITY" : "7",
"pCOMMENTS" : {
"Comment" : [ ]
}
}
],
"nextProductCounter" : 2
}
I want to add comments through a html form using php to add comment at db.
The best I've got is this, but seems to not work
$new_comm = array(
"username" => "guest",
"date" => new \MongoDB\BSON\UTCDateTime(strtotime(date('d-m-Y 00:00'))),
"text" => "excellent product",
"rating" => "4"
);
$collection->updateOne(
array("Products._id" => new MongoDB\BSON\ObjectId("60058012c34000008a00214b")),
array('$push' => array("Products.pCOMMENTS" => array("Comment"=>$new_comm)))
);
Why the pCOMMENTS array isn't updating?
Expected results
"pCOMMENTS" : {
"Comment" : {
"username" : "guest",
"date" : "18/1/2021",
"text" : "excellent product",
"rating" : "4"
}
}
You need to use positional operator
Reference
$collection->updateOne(
array("Products._id" => new MongoDB\BSON\ObjectId("60058012c34000008a00214b")),
array('$push' => array("Products.$.pCOMMENTS" => array("Comment"=>$new_comm)))
);

sum an array objects in laravel mongodb

I am working on mongoDB with Laravel using jenssegers. And i am trying to sum based on Abonos.price.
I have a MongoDb document like this:
`{
"_id" : ObjectId("594a89358b85112444002924"),
"cliente" : "blabla",
"tipo" : "bla bla",
"paquete" : "bla bla",
"date" : "2017-06-14",
"content" : "picture",
"cost" : NumberInt(200),
"status" : NumberInt(2),
"Abonos" : [
{
"price" : "200", `enter code here`
"date" : "2017-06-21"
},
{
"price" : "300",
"date" : null
}
], }`
I want to sum Abonos.price to get "500" (200+300)
I have this function in my laravel controller:
$result = Work::raw(function($collection){
return $collection->aggregate(array(
array('$unwind' => '$Abonos'),
array('$group' => array(
"_id" => '$_id',
"total" => array('$sum' => '$Abonos.price')
)),
));});
return $result;
But i get
[{"_id":"594a95cc8b85112444002925","total":0}
instead of
[{"_id":"594a95cc8b85112444002925","total":500}"
I would like to make $return = 500

MongoDB $in operator for an array stored in the same collection

If I have the following schema:
users = {
_id: MongoID
name: String,
email: String,
password: String,
online: Boolean, // Tells if user is online or not
friends: Array, // Storing _ids of friends
request: Array
}
Now, I want to get the name of all the friends which are online, sorted by name.
MongoDB database:
{
"_id" : ObjectId("572e43d71ccbdd080f00002b"),
"name" : "Bot 3",
"email" : "bot3#gmail.com",
"password" : "202cb962ac59075b964b07152d234b70",
"online" : false,
"friends" : [
ObjectId("572efe481ccbdd9c12000029")
],
"requests" : []
}
{
"_id" : ObjectId("572efe481ccbdd9c12000029"),
"name" : "Bot 4",
"email" : "bot4#gmail.com",
"password" : "202cb962ac59075b964b07152d234b70",
"online" : false,
"friends" : [
ObjectId("573074e81ccbddc816000029"),
ObjectId("572e43d71ccbdd080f00002b")
],
"requests" : [ ]
}
{
"_id" : ObjectId("573074e81ccbddc816000029"),
"name" : "Bot 5",
"email" : "bot5#gmail.com",
"password" : "202cb962ac59075b964b07152d234b70",
"online" : true,
"friends" : [
ObjectId("572efe481ccbdd9c12000029")
],
"requests" : [ ]
}
I want some query like:
var arr = db.users.find({"_id": ObjectId("572efe481ccbdd9c12000029")},
{"friends": 1, "_id": 0});
db.users.find({$in: arr["friends"]}, {"name": 1, "online": 1}).sort({"name": 1});
I tried this php code on the above example (not even close to requirement):
<?php
$cursor1 = $users->find(
array(
"_id" => new MongoID($id),
),
array(
"friends" => 1
)
);
$cursor1->next();
$doc1 = $cursor1->current();
$friend_arr = $doc1['friends'];
foreach($friend_arr as $f_id){
$cursor2 = $users->find(
array("_id" => new MongoID($f_id)),
array("name"=>1));
$cursor2->next();
$doc2 = $cursor2->current();
echo "<div>".$doc2['name']."</div>";
}
?>
But I know it does not satisfy the needs. That's why I am asking for help.
I am new to MongoDB with php.
Thank you so much in advance for any help.
Ok guys, I got the solution after some thinking.
$cursor1 = $users->find(
array(
"_id" => new MongoID($id),
),
array(
"friends" => 1
)
);
$cursor1->next();
$doc1 = $cursor1->current();
$friend_arr = $doc1['friends'];
$cursor2 = $users->find(
array(
"_id"=> array(
'$in' => $friend_arr
)
),
array(
"name" => 1
)
);
$cursor2->sort(array("name"=>1));
foreach($cursor2 as $doc2){
echo "<div>".$doc2['name']."</div>";
}
This code works properly. I tested it before posting.

Null set returned by mongodb aggregate Cursor in PHP

MongoDB aggregate query returning empty set .Below is the query i am using in a php script to retrieve data from mongoDB .Please let me know where i am going wrong.
$result = $collection->aggregateCursor([[ '$match'=> [ 'date'=> [ '$gte'=>ISODate("2015-06-01T00:00:00Z"), '$lte'=>ISODate("2015-06-03T00:00:00Z")] ] ],[ '$group'=> [ '_id'=> '$date', 'count'=> [ '$sum'=>1 ] ] ]]);
If i run same query in mongoDB shell.it is showing the output as expected.
db.mnumber.aggregate([{ $match: { date: { $gte:new ISODate("2015-06-01T00:00:00Z"), $lte:new ISODate("2015-06-03T00:00:00Z") } } },{ $group: { _id: "$date", 'count': { $sum:1 } } }])
{ "_id" : ISODate("2015-06-01T00:00:00Z"), "count" : 10000 }
{ "_id" : ISODate("2015-06-02T00:00:00Z"), "count" : 10000 }
{ "_id" : ISODate("2015-06-03T00:00:00Z"), "count" : 10000 }
Sample data in collection:
{
"_id" : ObjectId("55743941789a9abe7f4af3fd"),
"msisdn" : "1234567890",
"act_date" : ISODate("2014-11-24T00:00:00Z"),
"date" : ISODate("2015-06-07T00:00:00Z"),
"recharge_stats" : {
"recharge_amt" : 0,
"rechargetype" : "WEB"
},
"voice_usage" : {
"local_og_mou" : 20,
"local_other_mobile_og_mou" : 0,
"nld_og_mou" : 0,
"nld_other_mobile_og_mou" : 10
},
"gprs_usage" : {
"total_access_count" : 1,
"total_datavolume_mb" : 42
},
"sms_usage" : {
"freesms" : 3,
"local_sms_count" : 0,
"nat_sms_count" : 0,
"inter_sms_count" : 0
},
"campaign_details" : {
"camp_id" : "M01124",
"message" : "Hello .",
"msg_id" : "9174051951412054925609431100",
"cmp_activation_status" : "YES"
}
}
Try to generate a MongoDate() object as follows
$dateFrom = new MongoDate(strtotime("2015-06-01T00:00:00Z"));
$dateTo = new MongoDate(strtotime("2015-06-03T00:00:00Z"));
which you can then use in your aggregation pipeline instead of the MongoDB ISODate objects in your PHP query.
/* Run the command cursor */
$result = $collection->aggregateCursor(
[
[ '$match' => [ 'date'=> [ '$gte' => $dateFrom, '$lte' => $dateTo ] ] ],
[ '$group' => [ '_id' => '$date', 'count' => [ '$sum' => 1 ] ] ]
]
);

PHP MongoDB update doesn't work

{
"__v" : 2,
"_id" : ObjectId("54dc4fd10ac1f6a066a0646c"),
"desc" : "test1",
"lists" : [
{
"index" : 1,
"text" : "__point",
"_id" : ObjectId("54dc4fda0ac1f6a066a0646d"),
"createdAt" : ISODate("2015-02-12T07:01:46.390Z")
},
{
"index" : 2,
"text" : "__point",
"_id" : ObjectId("54dc4fdd0ac1f6a066a0646e"),
"createdAt" : ISODate("2015-02-12T07:01:49.668Z")
}
],
"name" : "test" }
The test array looks like this. i want to add 'category' field and add value '0' in lists checking _id.
i tried
$collection->update(array('_id' => new MongoId("54dc4fd10ac1f6a066a0646c")),array('$set' => array(new MongoId("54dc4fda0ac1f6a066a0646d").".lists.category" => '0')));
like this but it doesn't work.
set third parameter of update to true.
i think there is some problem in finding which embedded document for updated.
try this one might be work.
$collection->update(array('_id' => new MongoId("54dc4fd10ac1f6a066a0646c"), 'lists._id' => "54dc4fda0ac1f6a066a0646d"), array('$set' => array("lists.$.category" => '0')), true);
Hi I don't know more about PHP but you can do this from following script
db.collectionName.find({
"lists": {
"$exists": true
}
}).forEach(function(data){
for(vari=0;i<data.lists.length;i++){
db.collectionName.update({
"_id": data._id,
"lists.index": data.lists[
i
].index
},
{
"$set": {
"lists.$.category": 0
}
},
true,
true);
}
})

Categories