How to specify gender e multiple cip code facebook - facebook

I want to specify in the query gender and multiple zip:
act_xxxxx/reachestimate?currency=EUR&optimize_for=OFFSITE_CONVERSIONS&targeting_spec={ "geo_locations":{"zips":[{"key":"IT:89040"},{"key":"IT:87100"}]},"age_min": 20,"age_max": 40}
Another problem is that If I execute query I obtain this is the result:
{
"data": {
"users": 22000,
"estimate_ready": true
}
}
This result is the sum again the users of first zip code and the users of second zip code but I I do not want this, I want to read (in the result) the users of first zip code and the users of second zip code separately. Can Anyone help me?

Related

MongoDB: Searching for multiple strings in a field through C# client

I am working on MongoDB and C# client.
I am having the following data in collection:
1- { _id: xId, Desc: "ABC BLX CPO"}
2- { _id: yId, Desc: "ZNP CKL IOP ERKK"}
3- { _id: zId, Desc: "POL MIU WER XDF RRF"}
Now the issue is I have to search for dynamic values in Desc field depending upon user requirements. e.g
Searching for one string "ABC" at time,
Next time may be I have to search for two strings in Desc field "XYZ" and "IOP"
Next time may be I have search for five strings
I create a list of these search keywords(whether it is one, two or any number) and loop it through and search one by one :
list = ["ABC", "XYZ", "IOP"];
foreach(string item in list)
{
findInDB(item);
}
void findInDB(string val)
{
db.Collection.find({"Desc" : /val /i}) //pseudo code
}
Although the above code is working for me, but it takes too much time as I have a very rich database.
I am looking for some efficient way to achieve the goal. kindly guide me if there is any possibility.

Find DocumentId through Discovery GUI tool

I want to train my Discovery collection where I have already uploaded over 200 documents. I uploaded these documents through the GUI. Looking through the Discovery documentation, I know that I have will have to make API calls to train my collection since the training API has not been exposed through the GUI yet. As part of the training API calls I need to include a document that looks like this:
{
"natural_language_query": "{natural_language_query}",
"filter": "{filter_definition}"
"examples": [
{
"document_id": "{document_id_1}",
"cross_reference": "{cross_reference_1}",
"relevance": 0
},
{
"document_id": "{document_id_2}",
"cross_reference": "{cross_reference_2}",
"relevance": 0
}
]
}
My question is how should I get the documentIds for the documents that I have already uploaded? Is there a way to find this through the GUI? Or perhaps an API call that will return something like:
{
"document_name" = "MyDocument1",
"documentId" = "the_document_id_for_MyDocument1"
},
...
{
"document_name" = "MyDocumentN",
"documentId" = "the_document_id_for_MyDocumentN"
}
Or would the only way to get the documentIds would be to create a new collection and upload all of the documents through API calls directly and track the documentIds as I get them back?
Using the GUI, perform the following steps:
Input term(_id) in the "Group query results (Aggregation)"
textbox.
Under "Fields to return", select "Specify" to input
extracted_metadata
Note, that query and filter inputs should remain empty

Using "$and" and "$in" together

I have a collection friends which i am using to store all the friends and has the following fields
id , userid, friendid
I have a collection notes which stores user notes and has the following fields
id, userid , ownerid , privateorpublic
The rule is a user can only see notes he/she has created or notes created by his/her friends or notes that are public
To fetch that information i am writing my query this way. First, get all the ids of my friends separated by a comma. I dont know how to write the query to return comma delimited values but this query below I am hoping will return all the firneds of the user by the given id:
db.friends.find({ { friendid: { userid: 'jhdshh37838gsjj' } }
then get the notes where are either created by a friend or are public notes or are notes belonging to user
db.notes.find({ownerid:'jhdshh37838gsjj', privateorpublic:'public',{ $in: [ "3ghd8e833", "78hhyaysgd" ] }
I am new to MongoDB. Are my queries right?
Find query syntax : db.collection.find({queryFieldName: queryFieldValue}, {requiredFieldName: 1, NotRequiredFieldName: 0})
Thus, translating first query, you'd get "get me all documents from collection friends where friendId equals a string {'userId':'Id'}" which is not desired.
Query for "Get me all friend Ids of userid jhdshh37838gsjj and don't print anything else in results" : db.collection.find({userId:'jhdshh37838gsjj'}, {friendId:1, _id:0})
However, this'll not give output as comma separated values. You'll get output as follows (because every document is an independent object):
{friendId: 1}
{friendId: 2}
$in requires array as input and not comma separated values. To make an array of field values for a $in query, you need to some extra work like:
var friendIdsArr = [] //Initiate an array to store friend Ids
db.friends.find({'userId':'jhdshh37838gsjj'},{'friendId':1,'_id':0}).forEach(function(x) {friendIdsArr.push(x.friendId);} ); //Foreach result in query, push value to array.
The friendIdsArr will be [1,2]
db.notes.find({'ownerId':'jhdshh37838gsjj', 'privateOrPublic':'public',{$in: ["friendId": friendIdsArr]})
will give results, json documents, matching the given conditions.
Interestingly, your notes collection doesn't have a note field.
I'd recommend you to read mongodb official documentation and make a single query instead of two different queries.

Mongo db conditional query

being a newbie to mongo, stuck in a conditional query:
I want to perform a search on the basis of 3 criteria, first name, last name and email id:
below query works perfect when all the fields exist:
db.students.find( { $and: [ { first_name: /^Abc$/i }, { last_name: 'Xyz'},{email_id:'gd#he'} ]})
the problem is when I don't give an email id , the query dosen't returns any result as it considers the email id to be null and searches for the combination 'Abc Firtis null',
where as I want the below scenario to be fulfilled:
I have a collection of students:
- FirstName: 1. ABC 2. ABC 3.ABC
- LastName: 1.XYZ 2. XY 3. XZ
- EmailID: 1.abc#xyz 2.Ab#xy 3.Ab#xz
if one enters only the first name in the search it should return all the 3 results
if user enters first name and last name it should return first two results and if the user enters all three details it should return only 1 result.
Any leads would be highly appreciated.
You seem to be talking about "input" data being different for the queries you want to issue and how to contruct the query to ignore fields as criteria for which you have no input.
This is all really about how the input is being collected as to how you handle it, but it all boils down to that you "conditionally build" the query ( which is just a data structure anyway ) rather than statically define a query and somehow ignore null or empty data.
So if you have seperate variables, then you test each value and build the query:
var firstName = "abc",
lastName = "xy,
email = null,
query = {};
if (firstName) {
query.firstName = new RegExp("^"+firstName,"i")
}
if (lastName) {
query.lastName = new RegExp("^"+lastName,"i")
}
if (email) {
query.email = new RegExp("^"+email,"i")
}
db.students.find(query)
This would build a query object that would end up like this based on the inputs:
{ "firstName": /^abc/i, "lastName": /^xy/i }
So since there is no value in email then the condition is not included. The end result is the condition not provided is not even queried for and then you get the relevant matches.
The same approach is basically simplified if you have some structured input to begin with:
var params = {
firstName = "abc",
lastName = "xy"
};
var query = {};
Object.keys(params).forEach(function(key) {
if (params[key])
query[key] = new RegExp("^"+key,"i");
});
db.students.find(query);
And it's the same thing, but since you have all parameter keys in one place then you can iterate them to build the query rather than test individually.
This is generally the case where you have input from something like a web request with parameters that come into req.params or even req.body depending on your method of input. So if you structure your code to accept input into a similar object ( or already have it ) then you use it to build your query.
Also note that all MongoDB query arguments are implicitly an "AND" condition by definition, so there is rarely any need to use $and unless you explicitly have multiple conditions to meet for the same document property. Even then there are generally better syntax alternates.
No Need to give and you can simply try this
find( { first_name: { $regex: '/^Abc$/i' }, last_name:'Xyz',email_id:'gd#he'}

many small documents or less big documents

I have an application with many messages. Every user is able to select one message in order to send this message to an other user. Finally this message will get an flag ('message was send to: user1, user2,...) Those send informations should be stored in mongoDB.
Now I'm thinking about 2 different ways:
1.) many small documents in one collection
Every documents contains the message ID, the user name, who send this message and an Array of recipient, like this:
{
_id:'3DA5FC203,
sender:'username1',
recipient:['user1','user2','user3']
},
{
_id:'4AD290FC,
sender:'username1',
recipient:['user1','user2','user3']
},
{
_id:'4AD290FC,
sender:'usernameX',
recipient:['user2']
}
If 1000 users sends 10 messages a day to 1 ore more recipient, so if have 3.6 millions documents per year.
2.) less bigger documents in one collection
The other way would be less documents, but bigger one. For example one document for every message with the information about all the sender and recipient of this message. An mongoDB entry could look like that:
{
_id:'3DA5FC203,
'username1':['user1','user2','user3'],
},
{
_id:'4AD290FC,
'username1':['user1','user2','user3'],
'usernameX'['user2']
},
In this case: only 2 documents instead of 3 (example above), but one document could contain 100 or more sender.
So my question: which case will mongoDB handle better? Many small documents or less big? And which scenario is better for performing analyses, like: show all messages and recipient from one sender (username1)?
Using keys as values, like you do in:
'username1':['user1','user2','user3'],
is a bad idea as you can not do a indexed query where you look for documents that have a specific sender. This works:
db.messages.find( { 'username1' : { $exists: true } } );
But it is not going to be fast.
It is probably wise to keep your first option, with one document per message and sender.
Then you can just do:
db.messages.find( { sender: 'username1' } );
Adding a new recipient to this document can be done with:
db.messages.update(
{ 'msgid' : '867896', sender: "username1" },
{ 'recipient': { $push: "user4" } }
);
You can make MongoDB use the same index for both queries as well, by having:
db.messages.ensureIndex( { sender: 1, msgid: 1 } );
Other hints
You need to be aware that you also can not have two documents with the same _id value as you have in your first example. So you will have to make sure to add this ID as a different field than _id. For example:
{
msgid:'3DA5FC203,
sender:'username1',
recipient:['user1','user2','user3']
},
And let MongoDB just create the _id field for you.