PHP/MongoDB: update a value in an array - php

I have the following mongodb object:
{
"_id": ObjectId("4d0b9c7a8b012fe287547157"),
"messages": {
"0": {
"toUname": "Eamorr3",
"fromUname": "Eamorr2",
"time": 1292606586,
"id": "ABCDZZZ",
"subject": "asdf",
"message": "asdf",
"read": 0 //I want to change this to 1!
},
"1": {
"toUname": "Eamorr1",
"fromUname": "Eamorr3",
"time": 1292606586,
"id": "EFGHZZZ",
"subject": "asdf2",
"message": "asdf2",
"read": 0
}
},
"uname": "Eamorr3"
}
How do I set "read" to 1 where id=ABCDZZZZ? I'm using PHP.
I've tried the following command:
$driverInboxes->update(array('uname'=>$uname),array('$set'=>array('messages'=>array('id'=>$id,'read'=>'1'))));
But when I do this, overwriting occurs and I get:
{
"_id": ObjectId("4d0b9c7a8b012fe287547157"),
"messages": {
"id": "j7zwr2hzx14d3sucmvp5",
"read": "1"
},
"uname": "Eamorr3"
}
I'm totally stuck. Any help much appreciated.
Do I need to pull the entire array element, modify and and push it back in again?
Many thanks in advance,

If you read your command, you're actually saying: "UPDATE WHERE uname = Eamorr3 SET messages equal to this array (id=blah,read=1)"
When you do a $set on messages, you're basically instructing it to take your array as the new value.
However, it looks like you're trying to update a specific message as read which is just a little more complex. So there are two hurdles here:
1: You're actually updating messages.0.read
If you do array('$set' => array( 'messages.0.read' => 1 ) ), you will update the correct element. Follow that chain, messages is a javascript object and you want to update the property 0. The property 0 is itself a javascript object which contains the property read which you want to update.
Can you see how you're updating messages.0.read?
This brings us to problem #2.
2: the 0 is a problem for you
If you look at the way you've structured the data in Mongo, the messages object is really sub-par. The "0" and "1" are currently acting as "ids" and they're not very useful. Personally, I would structure your objects with the actual IDs in place of "0" or "1".
So your objects would look like the following:
{
"_id": ObjectId("4d0b9c7a8b012fe287547157"),
"messages": {
"ABCDZZZ": {
"toUname": "Eamorr3",
"fromUname": "Eamorr2",
"time": 1292606586,
"subject": "asdf",
"message": "asdf",
"read": 0 //I want to change this to 1!
}
},
"uname": "Eamorr3"
}
Now you're update command becomes this:
array('$set' => array( 'messages.ABCDZZZ.read' => 1 ) )
This structure makes it much easier to update a specific message or a specific portion of a message.

If you want to keep the array structure for various purposes, you can use the Positional operator. This enables you to take advantage of array features ($pop,$push,etc) while simultaneously being able to update elements which are in an unknown array position.

Related

JSONPath: how to get empty string (or null) if path (field) not exist?

Incoming JSON:
[
{
"name": "Name1"
},
{
"name": "Name2"
},
{
"name": "Name3",
"surname": "Surname3"
}
]
If we use JSONPath like $[:].name, we will receive:
[
0: "Name1",
1: "Name2",
2: "Name3"
]
But if will use the same to get surname ($[:].surname), we will receive:
[
0: "Surname3"
]
Is this possible to get surname values with empty string (or nulls) to keep right indexes? E.g.
[
0: "",
1: "",
2: "Surname3"
]
P.S.: at the moment I'm using this library.
JSON Path doesn't support returning placeholder values like that. It's a query language for JSON documents, much like SQL is for relational databases. Could you imagine if a SQL query returned placeholder values for every record in a database that didn't match your query?
I expect that the reason you want this is to determine where in the original document the value appears. To that end, JSON Path implementations should support returning the paths to the values instead of the values themselves:
[
"$[2]['surname']"
]
But I can't see in the README of that library where such a feature is supported (though it still might).

I want a more consolidate json format

I am getting json array after getting applying query logic.
[
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-20"
},
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "CRP",
"booking_date": "2018-05-20"
},
{
"id": "4",
"diag_name": "Seepz Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-21"
}
]
But i want a more justified json array written below.
[
{
"diag_name": "LT Diagnostics",
"test_name": [
{
"id": "3",
"name" : "Alk PO4"
},
{
"id": "3",
"name" : "CRP"
}
],
"booking_date": "2018-05-20"
},
{
"diag_name": "Seepz Diagnostics",
"test_name": [
{
"id": "4",
"name" : "Alk PO4"
}
],
"booking_date": "2018-05-21"
},
]
I am not getting it,How to do in php. I want a more consolidate json format.
Have you tried changing your SQL query to group by diag_name and booking_date? That would be the first step I’d employ to get the outer data.
Formatting the data in the nested manner you’re after could be a function of whatever record serializer you’re using — does it support nested JSON as a return type, or only flat JSON as your example return value shows?
If the record set -> JSON serializer only ever returns flat data, the comments above are correct that you will have to write your own formatter to change the shape of the JSON yourself...
The accepted answer of this other question may be of help:
Create multi-level JSON with PHP and MySQL
I'm not a PHP guy but this is a typical scenario to use functional programming by means of the monad Map.
Looking online I've found this article that could help you.
Changing datasource output is not always (seldom indeed) a viable option.
Enjoy coding

find() query MongoDB for php

Hi i am using mongoDb for my new project. I am trying to find values from mongodb database.
My mongoDB database collection name is: test and json format is below
{
"College": [
{
"name": "tamy",
"roll_no": "1"
},
{
"name": "abhi",
"roll_no": "2"
},
{
"name": "jack",
"roll_no": "3"
}
],
"School": [
{
"name": "zack",
"roll_no": "1"
},
{
"name": "mac",
"roll_no": "2"
},
{
"name": "john",
"roll_no": "3"
}
]
}
**And i want to find the name:abhi from test collection **
and my mongodb find query in php
$criteria = array(
'College'=> array(
'name'=> 'abhi'
));
$cursor = $collection->find($criteria);
but its not returning any value.
if i am displaying in php by using print_r.
print_r(iterator_to_array($cursor));
displaying empty array()
I need output like this:
name : jack
roll_no : 3
plz help me..
The key "College" is an array, your trying to treat it as a "subdocument" (but that wouldnt allow for multiple colleges to be stored)
You want the elemMatch keyword here I believe: http://docs.mongodb.org/manual/reference/operator/query/elemMatch/
EDIT: After looking at this again, I think you have your structure a little out of whack. How many "students" will there be per college or school? Keep in mind each parent document can not exceed 10mb, and when you select a document, the entire document must be sent back across the connection (unless you are using aggregate or map/reduce. I would think you may want to have a collection of Persons and then a key associating a person to... something else.

How to update mongodb document

Hi i'm really mongodb newbie.
I have a document like this:
{
"_id": ObjectId("53182e32e4b0feedb1dea751"),
"solutions": [
[
{
"solution": "Double Room Economy (Without Breakfast)",
"board": "Room Only",
"id": "HK-15501871",
"price": 5000,
"available": "1",
"CXL": "[]",
"unique": 0
},
{
"solution": "Double Room Economy (With Breakfast)",
"board": "Room Only",
"id": "HK-15501871",
"price": 4600,
"available": "1",
"CXL": "[]",
"unique": 1
},
{
"solution": "Double Room Economy (Room Only)",
"board": "Room Only",
"id": "HK-15501871",
"price": 5500,
"available": "1",
"CXL": "[]",
"unique": 2
}
]
]
}
And i need to update the field CXL inside the second array of solutions.
so solutions.1.CXL
This is how i take document:
$collection = $this->getCollection();
$query = array("_id"=>new MongoId($id));
$document = $collection->findOne($query);
now i need to update that field without touch the other.
How can i do?
Thanks!
SOLVED THANKS TO #Sammaye
i solved in this way:
$collection->update(
array('_id' => new MongoId('..')),
array('$set' => array('solutions.0.1.CXL' => 'something'))
);
Edit
To actually update by the first index then you can do:
$db->collection->update(
['_id' => new \MongoId($id)],
['$set' => ['solutions.0.1.CLX' => 'whatever']]
);
I misread the question in posting the information below:
So what you wanna update all CXL fields in the document (since you are only searching by top level document _id)?
That isn't possible without manually pulling this document out and iterating the subdocuments in the solutions field and then resaving it.
This is becausde there is currently no way of saying, "Update all that match"
This, however, is most likely the JIRA you would want to look for: https://jira.mongodb.org/browse/SERVER-1243
As long as you know you are going to update the second element then use the index of the array to do so. But that problem next. First you need the $set operator in order not to blow away your document and just set the field value:
db.collection.update(
{ _id: ObjectId("53182e32e4b0feedb1dea751") },
{ $set: { "solutions.0.1.CXL": [ 1, 2, 3 ] } }
)
If you just want to add to the array rather than replace the whole thing, then just use $push instead:
db.collection.update(
{ _id: ObjectId("53182e32e4b0feedb1dea751") },
{ $push: { "solutions.0.1.CXL": 4 } }
)
If you are paying attention to the notation, then you will notice that the array index values are present in the field to be updated. There is a very good reason for this, which can be read on the documentation for the positional $ operator.
The issue is that you have a nested array, which as the documentation refers to, causes a problem if you try to match items within that nested array. That problem is, if you try to use the "positional" operator to find the matched index of something you look for in a query, then it will contain the value of the first array index match that it finds.
In this case that would be your "top level" array and the "found" index is 0 and not 1 as you may expect.
Please be aware of this issue if you intend to use nested arrays.
You can update like this:
update({
_id: ObjectId("53182e32e4b0feedb1dea751"),
solutions.id: HK-15501871,
solutions.CLX: "Whatever!",")
},{
$set: {"comments.$.type": abc}
}, false, true
);
You may want to go through this once
http://docs.mongodb.org/manual/reference/method/db.collection.update/

Using AND on same key in mongodb

I have a key in my document whose structure is as follow:
"tag": [
{
"schemeName": "http:\/\/somesite.com\/categoryscheme2",
"name": "Test Tag2",
"value": 1,
"slug": "test_tag2"
},
{
"schemaName": "http:\/\/somesite.com\/categoryscheme3",
"name": "Test Tag3",
"value": 1,
"slug": "test_tag3"
}
]
Now, I get inputs as tag=test_tag2ANDtest_tag3. How can I write a query for this?
I tried to iterate through the loop but I didnt got any results.
Correct me if I am wrong but you don't need an $and or $elemMatch, instead:
$mongodb->collection->find(array('tags.slug'=>array(
'$in' => array('test_tag2','test_tag3'))))
Should work, however, if your English suggests what a second read does, then you can also use $all in place of $in. This will ensure that all root documents must have those slugs in them.
use $elemMatch operator to match elements inside the array.

Categories