How to query for an empty string in PHP Mongo? - php

I'd like to query for all documents in my collection where the field client is an empty string. I've seen plenty of examples of how to check if something's not an empty string but I can't find any examples of how to do the opposite. I've tried db.collection.find({client: ""}) but I get back an empty set.
EDIT: The example entry in the collection looks like
{ "_id" : ObjectId("54eb59699e12a795078b80da"), "reportID" : "1472031", "orgID" : "336", "client" : "", "customerID" : NumberLong(1), "address" : "123 main st", "city" : "Grove City", "state" : "OH", "zip" : "43123", "county" : "Franklin", "gpsLatitude" : null, "gpsLongitude" : null, "dateDue" : ISODate("2012-08-18T00:00:00Z"), "dateDueClient" : ISODate("2012-08-18T00:00:00Z"), "dateComplete" : ISODate("2012-08-18T00:00:00Z"), "dateCompleteEstimate" : NumberLong(0), "contractorSubmissionDate" : ISODate("2012-08-19T00:26:23Z"), "createdOn" : ISODate("2012-08-19T00:21:37Z"), "assignedToContractorOn" : ISODate("2012-08-19T00:21:37Z"), "workTypeID" : "6338", "assignedAdmin" : "7880", "contractorID" : "7880", "categoryID" : "0", "historyLength" : NumberLong(0), "invoiceDate" : ISODate("2012-08-18T00:00:00Z"), "submittedToClient" : ISODate("2012-08-18T00:00:00Z"), "paymentContractor" : NumberLong(0), "paymentClient" : NumberLong(0), "contractorIsPaid" : NumberLong(0), "clientIsPaid" : NumberLong(0), "sentinel" : NumberLong(1), "isFrozen" : NumberLong(0), "numTimesClientReady" : "1", "pcrResponses" : [ ] }
There's a lot of fields but the client one is pretty close to the beginning.

The query you posted should work. Just to verify, I inserted that data as a row in a test collection, and it was returned right back out with db.test.find({client: ''})
I'm thinking you may have a problem somewhere else. I've once or twice been in the wrong database when running queries, or had a typo in the collection name. To verify what my data looks like, I'll often times:
> db.tset.find({client: ''});
[] // What? No results? ...backspacebackspacebackspace
> db.tset.find();
[] // What? No results at all for no query? I must be in the.. OH!
> db.test.find();
[] // What? I thought I had a typo in my collection name. What database am I in?
> db
tseting // OH! I keep making that typo..
> use testing
switched to db testing
> db.test.find({client: ''});
[] // What? Still no results? This is weird...
> db.test.insert({client: ''});
> db.test.find({client: ''});
{ "_id" : ObjectId("54f1b5e5d05052fce4fb6684"), "client" : "" }
// Hmm, ok, so there's nothing wrong with the query. The data came up
// So I'm still just in the wrong place? Really?
// Maybe I woke up on the wrong side of the bed today. I should eat lunch.
Sometimes tunnel vision makes you think the problem lies somewhere that it doesn't. Leave a comment if this is or isn't helpful, maybe we can come up with some more troubleshooting ideas.

Related

add object id mongo db php document

{
"_id" : ObjectId("5844dd1d3627570f004612a5"),
"updatedBy" : ObjectId("57c4799d23be243006e188f8"),
"updatedAt" : ISODate("2016-12-21T10:08:10.211Z"),
"createdBy" : ObjectId("5801b7195248ef0e00948934"),
"createdAt" : ISODate("2016-12-05T03:21:01.660Z"),
"stock" : 50,
"price" : 15000,
"owner" : ObjectId("5801b7195248ef0e00948934"),
"type" : ObjectId("57dce9ad07f96c701c0b24a8"),
"isValid" : true,
"grade" : "Grade A",
"__v" : 0
}
i want to ask how to insert owner data and also type data as ObjectID to mongoDB with php
when i just insert data, it wont changes to object id
anyone?
i got the answer.
just use like this :
$id_param = 1270982704y1024kjh12kj4h; new MongoId($id_param)
thanks a lot your for help

Intelligent searching with mongo

I am using phalcon with mongodb. I have the following document in collection:
{
"_id" : ObjectId("547c8b6f7d30dd522b522255"),
"title" : "Test vacancy",
"slug" : "test-vacancy",
"location" : "the-netherlands",
"contract" : "fixed",
"function" : "Test vacancy",
"short_description" : "gdfsgfds",
"description" : "fdsafsdgfsdgdfa",
"promo_text" : "gfdsgdfs",
"company_name" : "gfdsgfsd",
"hits" : 36,
"updated_at" : 1.42685e+09,
}
In controller I am fetching all results by searched phase/query. For example I put example word and output will be all posts with example word in description or title or short_desc etc. Everything is correct but I want sort these posts in specific order. I mean if query will be same as title, this post should be first. Now it is somewhere below.
Can you help me? Thank you in advance.

Mongo and Yii -> update with $set a field in all the arrays of a subdocument

I'm having problems updating a specific field in all the arrays of a subdocument. I have the following structure in MongoDB:
{
"_id" : ObjectId("539c9e97cac5852a1b880397"),
"DocumentoDesgloseER" : [
{
"elemento" : "COSTO VENTA",
"id_rubroer" : "11",
"id_documento" : "45087",
"abreviatura" : "CV",
"orden" : "1",
"formula" : "Cuenta Contable",
"tipo_fila" : "1",
"color" : "#FFD2E9",
"sucursal" : "D",
"documentoID" : "0",
"TOTAL" : "55426.62",
},
{ ... MORE OF THE SAME ... }
],
"id_division" : "2",
"id_empresa" : "9",
"id_sucursal" : "37",
"ejercicio" : "2008",
"lastMonthNumber" : NumberLong(6),
}
I need to update the field "documentoID" to a specific value; like "20" for example, in all the arrays of the subdocument "DocumentoDesgloseER". How I can do this?
I tried the following (with $ operator) and is not working:
$querySearch = array('id_division'=>'2', 'id_empresa'=>'9', 'id_sucursal'=>'37', 'ejercicio'=>'2008');
$queryUpdate = array('$set'=>array('DocumentoDesgloseER.$.documentoID'=>'20'));
Yii::app()->edmsMongoCollection('DocumentosDesgloseER')->update($querySearch,$queryUpdate);
By the way, I'm using Yii Framework to make the connection with Mongo. Any help or advice is welcome.
Thanks ;D!
Unfortunately, you can't currently use a positional operator to update all items in an array. There is a ticket opened in the MongoDB JIRA about this issue.
There a two "solutions":
Change your schema so that your embedded documents are in the separate collection (it's probably not what you want).
The best you can do, if you don't want to change your schema, is to update each subdocument in PHP and then save the whole document.

Reading Json returned by MongoDB in PHP

I got a task to get to find out ER from json files this is the one record
{ "__v" : 0, "_id" : ObjectId( "52210bf6880b9f0200000003" ), "email" : "", "emailFrequency" : "instant", "feedbackRating" : 0, "field_aboutMe" : "On Fridays I like to eat apples.", "field_contact" : "me#matt.is", "field_intro" : "Sparkboard bug-fixer. Co-founded Hacking Health, Bodo Wellness, and BrainTripping.", "first_time" : false, "hash" : "", "name" : "Matt Huebert", "picture" : "https://www.ssss.com", "ready" : true, "roles" : [ "admin" ], "email" : "", "tags" : [ "Developer", "Designer", "Mentor" ], "updatedAt" : Date( 1384115378947 ), "votesByDomain" : { "sadsard-com" : "525eadf50f13910200000004" } }
after searching i found out it has something to do with MongoDB . I need to parse this data to find out Entities in it . when i check its validation its not a valid json as its been generated by mongo db .
Please any body have any idea ?
Ive tried this as well
$data = file_get_contents('json/users.json');
bson_decode($data);
tried json_decode as well its also not working and returning NULL
I get this error while trying to bson_decode
Fatal error: Uncaught exception 'MongoException' with message 'type 0x5f not supported
Not sure what has dumped this into your json file, possibly from stdout of mongo shell, But this part is the problem:
ObjectId( "52210bf6880b9f0200000003" )
You need to remove the Wrapping "ObjectId(" and closing brace ")" in order to make each line valid JSON. Once that is filtered you are left with valid JSON.
If you know who is providing you with these files, and cannot use the mongodb datasource directly, then ask them to please use mongoexport, which will at least give you valid JSON from the start.

MongoDB Map Reduce newbie (PHP)

I'm new to the map reduce concept and even though I'm making some slow progress, I'm finding some issues that I need some help with.
I have a simple collection consisting of an id, city and and destination, something like this:
{ "_id" : "5230e7e00000000000000000", "city" : "Boston", "to" : "Chicago" },
{ "_id" : "523fe7e00000000000000000", "city" : "New York", "to" : "Miami" },
{ "_id" : "5240e1e00000000000000000", "city" : "Boston", "to" : "Miami" },
{ "_id" : "536fe4e00000000000000000", "city" : "Washington D.C.", "to" : "Boston" },
{ "_id" : "53ffe7e00000000000000000", "city" : "New York", "to" : "Boston" },
{ "_id" : "5740e1e00000000000000000", "city" : "Boston", "to" : "Miami" },
...
(Please do note that this data is just made up for example purposes)
I'd like to group by city the destinations including a count:
{ "city" : "Boston", values : [{"Chicago",1}, {"Miami",2}] }
{ "city" : "New York", values : [{"Miami",1}, {"Boston",1}] }
{ "city" : "Washington D.C.", values : [{"Boston", 1}] }
For this I'm starting to playing with this function to map:
function() {
emit(this.city, this.to);
}
which performs the expected grouping. My reduce function is this:
function(key, values) {
var reduced = {"to":[]};
for (var i in values) {
var item = values[i];
reduced.to.push(item);
}
return reduced;
}
which gives somewhat an expected output:
{ "_id" : ObjectId("522f8a9181f01e671a853adb"), "value" : { "to" : [ "Boston", "Miami" ] } }
{ "_id" : ObjectId("522f933a81f01e671a853ade"), "value" : { "to" : [ "Chicago", "Miami", "Miami" ] } }
{ "_id" : ObjectId("5231f0ed81f01e671a853ae0"), "value" : "Boston" }
As you can see, I still haven't counted the repeated cities, but as can be seen above, for some reason the last result in the output doesn't look good. I'd expected it to be
{ "_id" : ObjectId("5231f0ed81f01e671a853ae0"), "value" : { "to" : ["Boston"] } }
Has this anything to do with the fact that there is a single item? Is there any way to obtain this?
Thank you.
I see you are asking about a PHP issue, but you are using javascript to ask, so I’m assuming a javascript answer will help you move things along. As such here is the javascript needed in the shell to run your aggregation. I strong suggest getting your aggregation working in the shell(or some other javascript editor) in general and then translating it into the language of your choice. It is a lot easier to see what is going on and there faster using this method. You can then run:
use admin
db.runCommand( { setParameter: 1, logLevel: 2 } )
to check the bson output of your selected language vs what the shell looks like. This will appear in the terminal if mongo is in the foreground, otherwise you’ll have ot look in the logs.
Summing the routes in the aggregation framework [AF] with Mongo is fairly strait forward. The AF is faster and easier to use then map reduce[MR]. Though in this case they both have similar issues, simply pushing to an array won’t yield a count in and of itself (in MR you either need more logic in your reduce function or to use a finalize function).
With the AF using the example data provided this pipeline is useful:
db.agg1.aggregate([
{$group:{
_id: { city: "$city", to: "$to" },
count: { $sum: 1 }
}},
{$group: {
_id: "$_id.city",
to:{ $push: {to: "$_id.to", count: "$count"}}
}}
]);
The aggregation framework can only operate on known fields, but many pipeline operations so a problem needs to broken down with that as a consideration.
Above, the 1st stage calculates the numbers need, for which there are 3 fixed fields: the source, the destination, and the count.
The second stage has 2 fixed fields, one of which is an array, which is only being pushed to (all the data for the final form is there).
For MR you can do this:
var map = function() {
var key = {source:this.city, dest:this.to};
emit(key, 1);
};
var reduce = function(key, values) {
return Array.sum(values);
};
A separate function will have to pretty it however.
If you have any additional questions please don’t hesitate to ask.
Best,
Charlie

Categories