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)))
);
Related
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
I am using codeigniter with mongodb library https://github.com/intekhabrizvi/Codeigniter-mongo-library
below is my collection "users". I want to count all the badges which has badge_slug = 100_club for userid 57b83ae9faa76bac338b4579 from users collection.
{
"_id" : ObjectId("57b83ae9faa76bac338b4579"),
"displayname" : "test",
"email" : "test#gmail.com",
"badges" : [
{
"awarded_at" : ISODate("2015-04-21T05:52:06Z"),
"object_id" : "",
"badge_slug" : "100_club"
},
{
"awarded_at" : ISODate("2015-04-21T06:12:14Z"),
"object_id" : "",
"badge_slug" : "100_club"
},
{
"awarded_at" : ISODate("2015-04-21T07:09:55Z"),
"object_id" : "",
"badge_slug" : "reader"
}
]
}
what I have done is
$ops = array(
array(
"$project" => array(
"count" => array(
"$size" => array(
"$filter" => array(
"input" => "$badges",
"as" => "badge",
"cond" => array("$eq" => => array("$$badge.badge_slug", "100_club") )
)
)
)
)
),
array(
"$group" => array(
"_id" => null,
"total" => array( "$sum" => "$count" )
)
)
);
$this->mongo_db->aggregate("users", $ops);
So the result should be 2 for given document.
But its returning count for all users. Where should I need to give userid condition?
You can use $match to filter documents before they're passed to next stage.
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.
{
"__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);
}
})
I want to query for a particular value inside array and update it and i dont know the index. Here are the contents.
{ "_id" : ObjectId("50072b17b4a6de3b1100000f")
"employment_details" : [
{
"_id" : ObjectId("50072b17b4a6de3b11000015"),
"title" : "Information Technology Compliance & Security",
"rank" : null,
"department" : null,
"current" : false,
"company_id" : ObjectId("5007269fb4a6de941001d19d")
}
......
{
"_id" : ObjectId("50072b17b4a6de3b11000018"),
"title" : "security engineer",
"rank" : null,
"department" : null,
"current" : false,
"company_id" : ObjectId("5007269fb4a6de941001dasd")
}
{
"_id" : ObjectId("50072b17b4a6de3b11000016"),
"title" : "software Engineer",
"rank" : null,
"department" : null,
"current" : true,
"company_id" : ObjectId("5007269fb4a6de94100189e")
}
]
I want to change the particular current field of particular object inside array(i dont know the index) inside employment_details if _id matches ObjectId("50072b17b4a6de3b1100000f") and company_id matches ObjectId("5007269fb4a6de94100189e").
Here is what I ve done. But not updating.
$criteria = array("_id" => $mongo_id, "employment_details.company_id" => $company_id);
$new_object = array('$set' => array('employment_details.$.current' => "false", "updated_at" => $time));
$mycollection->update($criteria,$new_object);
How to do such a update?