PHP MongoDB Search in Sub-array - mongodb

Data stored in collection as below
[field_1] => Array
(
[fields] => Array
(
[0] => MongoInt64 Object
(
[value] => 1233
)
[1] => MongoInt64 Object
(
[value] => 1234
)
)
)
I need to search 1234 in field.
I used below code in php to search
$param = array('field_1.fields.$' => 1234);
But this is not working

You need to use the $in query criteria, to find elements within an array
$cursor = $collection->find(array("field_1.fields" => array('$in' => array("1234"))));
This will find all items that have 1234 within "fields"
$in doc: https://docs.mongodb.org/v3.0/reference/operator/query/in/

Related

yii2 mongodb - how to find element in collection subarray

Array from collection looks like this.
$result = $collection->find();
Array
(
[0] => Array
(
[_id] => MongoDB\BSON\ObjectId Object
(
[oid] => 5c52b90454851c44aa2987e2
)
[name] => Array
(
[date] => 2019-01-31 10:59:48
[value] => DESKTOP-TODTF5E
)
[network_addresses] => Array
(
[0] => Array
(
[ip_1] => 12.21.134
[ip_2] => 50
[mac] => xx:xx:xx:xx:xx:xx
)
[1] => Array
(
[ip_1] => 192.168.0
[ip_2] => 2
[mac] => yy:yy:yy:yy:yy:yy
)
)
)
)
I can find if some mac exist in specific row of sub array like this:
$result = $collection->find(["network_addresses.0.mac" =>
"xx:xx:xx:xx:xx:xx"]);
But I need to check if certain mac exists in any row of subarray, so instead of row index 0 I need to put some asterix or something.
How to do that ?
$query = (new Query)->select(["name"])
->from(['db_name','collection_name'])
->where(["network_addresses" => [ '$elemMatch' =>['mac' => "xx:xx:xx:xx:xx:xx"]]]);
$results = $query->all();

MongoDB finding nested objects that meet criteria

I have a MongoDB document that is structured similar to the structure below follows. I am searching based on people.search_columns.surname and people.columns.givenname. So for example, when I search for the given name of "Valentine", I want to get the document back, but Nicholas Barsaloux should not be included.
Data structure:
[_id] => MongoId Object (
[$id] => 53b1b1ab72f4f852140dbdc9
)
[name] => People From 1921
[people] => Array (
[0] => Array (
[name] => Barada, Valentine
[search_columns] => Array (
[surname] => Array (
[0] => Mardan,
[1] => Barada
)
[givenname] => Array (
[0] => Valentine
)
)
)
[1] => Array (
[name] => Barsaloux, Nicholas
[search_columns] => Array (
[surname] => Array (
[1] => Barsaloux
)
[givenname] => Array (
[0] => Nicholas
)
[place] => Array (
)
)
)
)
Here is the code I was working on:
$criteria = array("people" => array(
'$elemMatch' => array("givenname" => "Valentine")
));
$projection = array("people" => true);
$documents_with_results = $db->genealogical_data->find($criteria, $projection)->skip(0)->limit(5);
Currently that code returns zero results.
Since the arrays are nested you cannot use basic projection as you can with find. Also in order to "filter" the array contents from a document you need to "unwind" the array content first. For this you use the aggregation framework:
$results = $db->genealogical_data->aggregate(array(
array( '$match' => array(
'people.search_columns.givenname' => 'Valentine'
)),
array( '$unwind' => '$people' ),
array( '$match' => array(
'people.search_columns.givenname' => 'Valentine'
)),
array( '$group' => array(
'_id' => '$id',
'name' => array( '$first' => '$name' ),
'people' => array( '$push' => '$people' )
))
));
The point of the first $match stage is to reduce the documents that possibly match your criteria. The second time is done after the $unwind, where the actual "array" items in the document are "filtered" from the results.
The final $group puts the original array back to normal, minus the items that do not match the criteria.

How to keep orders in MongoDB?

In my MongoDB document I have object like this
[_id] => MongoId Object (
[$id] => 52a46b44aabacb5c218b4567
)
[results] => Array (
[http://google.com] => Array (
[position] => 1
[data] => 42672
)
[http://bing.com] => Array (
[position] => 2
[data] => 9423
)
[http://yandex.com] => Array (
[position] => 3
[data] => 5513
)
)
I would like to change data parameter in "bing.com" from 9423 to for instance 300. Moreover, I have to keep order of the sites. It have to looks like this
[_id] => MongoId Object (
[$id] => 52a46b44aabacb5c218b4567
)
[results] => Array (
[http://google.com] => Array (
[position] => 1
[data] => 42672
)
[http://bing.com] => Array (
[position] => 2
[data] => 300
)
[http://yandex.com] => Array (
[position] => 3
[data] => 5513
)
)
Is this achievable in Mongo?
The reordering of fields issue has been fixed as of MongoDB v2.5.2 (2.6 release). Having said that one way you can avoid the issue completely is having results as an array instead of a (sub)document. Also note you should not use "." as part of the key name either.
With 2.4, with the following you will see there is reodering in the case of _id=1 (subdocument) but not in the case of _id=2 (array).
$document = array("_id" => 1, "results" => array('http://google.com' => array('position' => 1, 'data' => 42672),
'http://bing.com' => array('position' => 2, 'data' => 9423),
'http://yandex.com' => array('position' => 3, 'data' => 5513)));
$coll->insert($document);
$document = array("_id" => 2, "results" => array(array('site' => 'http://google.com', 'data' => 42672),
array('site' => 'http://bing.com', 'data' => 9423),
array('site' => 'http://yandex.com', 'data' => 5513)));
$coll->insert($document);
$coll->update(array("_id" => 1), array('$set'=>array("results.http://bing.com.data"=>300)));
$coll->update(array("_id" => 2, 'results.site' => 'http://bing.com'), array('$set'=>array('results.$.data'=>300)));
I've included examples below using the mongo shell for clarity, but the PHP equivalent should be straightforward to work out.
I notice you originally modelled your list of sites as an embedded document, however the order of fields within an embedded document is currently not guaranteed to be preserved so you should instead use an array.
Additionally, you cannot use field names with embedded dots (.) in MongoDB so you should not plan to store urls as field names (see: Field name restrictions).
In order to find an element in an array you need to search by a value (not a field name) so your schema should look more like:
{
_id: ObjectId("52a46b44aabacb5c218b4567"),
results: [
{
site: 'http://google.com',
position: 1,
data: 42762
},
{
site: 'http://bing.com',
position: 2,
data: 9423
},
{
site: 'http://yandex.com',
position: 3,
data: 5513
}
]
}
Assuming the array site elements are unique, you can use the positional operator $ to find and update the matching embedded document in place.
For example, to perform your update of the "bing.com" data value:
db.sites.update(
// Match criteria
{
_id:ObjectId("52a46b44aabacb5c218b4567"),
'results.site':'http://bing.com'
},
// Update
{ $set: {
'results.$.data': 300 }
}
)
In MongoDB 2.4+ you have the option of pushing to a sorted array which could also be a useful approach to maintaining your array in sorted order when you add new entries.
It's worth noting that if you plan to store many (i.e. thousands) of items in an array this can impose a significant performance penalty due to document growth and the complexity of updating large arrays.
I am pretty sure that (as every other DBMS) you can't and should't rely on records orders.
Instead I would advice you to add index (on position, i.e. db.people.ensureIndex( { position: 1 } )) and query your record sorted by that field, i. e.: db.collection.find().sort( { position: 1 } )

Search in multiple array in mongodb

I want to Search a value in an array Like
`[_id] => MongoId Object (
[$id] => 511f4ce622efc34f15000001
)
[metadata] => Array (
[filename] => 6410-funny_face.gif
[parrent] => myfolder/newfolder2
[user] => Array ( >>>>>>>> i need to fetch all users
[root] => 7
[admin] => 7
[user] => 0
)
[group] => Array (
[23] => 2
)
)
[filename] => 6410-funny_face.gif
[uploadDate] => MongoDate Object (
[sec] => 1361005798
[usec] => 799000
)
[length] => 3083
[chunkSize] => 262144
[md5] => eb3846f78f461165e5bf59a05707edd1`
I need to find the user's key and value in PHP or MongoShell
im using db.collection.find(array(metadata.filename: 6410-funny_face.gif)); gives the correct answer but while in finding db.collection.find(array(metadata.user: array(7)));
db.collection.find({"metadata.user.root":7})
This should work if I understand your question.

Populate date in MultiOptions element of Zend Form

Hello I have an array like this :
Array (
[id] => 1
[code] => Dep98
[description] => Hello World
[facility] => Array (
[0] => FacName1
[1] => FacName2
)
)
But when I populate this array to Zend_Form it only show data in textboxes elements having same id as defined in array index not in multiselect dropdown element. for example:
'code' id is also define in form's first textbox element,
'description' id is also define in form's second textbox element,
'facility' id is also define in form's third MultiOptions element
But in MultiOptions it does not show any record.
I agree with Travis, you should pass an array with following values to populate:
$vals = array('code'=>5,
'description' => 'testing',
'facility' => array(1=>'FacName2'));
$form->populate($vals);
But note this - options must be filled in the facility form element before attempting to populate or validate, dont expect facility value to be set if there is an empty list of options in the facility element.
What exactly do you want in the drop down box?
The array you pass to multiOptions must be in the form of value => title.
You may want to loop through your results and generate an options array.
For example
$options = array();
foreach ( $data as $value ) {
$options[$value['id']] = $value['description'];
}
$select = Zend_From_Element_Select("select_field");
$select->multiOptions($options);
Try this:
Array (
[id] => 1
[code] => Dep98
[description] => Hello World
[facility] => Array (
FacName1 => [0]
FacName2 => [1]
)
)