Find MongoDB records where array field is empty - mongodb

I need to output a list of sketchid values for which tdata birthdate is not present/null, considering only the first birthdate in each tdata.
There are many fields in each collection, but I am only interested in two of them:
{
"sketchid": NumberLong(51148),
"tdata": "[
{ "birthdate": ["529718400"], ...},
{ "birthdate": null, ... }
]
}
I need to print the sketchid for each tdata in which the first birthdate is empty.
Note: A single tdata contains many birthdate fields, I need to check only the first birthdate field and if it is empty I need to output the sketchid for that set.
I have tried this, but I couldn't get the solution.
db.timeline.find({tdata:{birthdate:{$exists: true, “$ne”: null }}},{sketchid})
To illustrate the data schema, the find() command (db.timeline.find().pretty()) gives the following output:
{
"_id" : ObjectId("56ea7b9490e2a5b17c143b56"),
"sketchid" : NumberLong(51147),
"tdata" : "[{\\\"type\\\":\\\"dob\\\",\\\"title\\\":\\\"Vishakha Singh\\\",\\\"year\\\":null,\\\"color\\\":null,\\\"content\\\":\\\"\\\",\\\"birthdate\\\":[\\\"831254400\\\"],\\\"birthplace\\\":[\\\"Abu Dhabi, UAE\\\"],\\\"zodiac\\\":\\\"Taurus\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"Cameo Role\\\",\\\"year\\\":[\\\"2014\\\"],\\\"color\\\":[\\\"#85330B\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Tamil movie Oru Oorla Rendu Raja&quot;]" data-sheets-userformat="[null,null,513,[null,0],null,null,null,null,null,null,null,null,0]">Tamil movie Oru Oorla Rendu Raja<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"Noticable Flick\\\",\\\"year\\\":[\\\"2013\\\"],\\\"color\\\":[\\\"#21C8F5\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Neetu in Fukrey&quot;]" data-sheets-userformat="[null,null,513,[null,0],null,null,null,null,null,null,null,null,0]">Neetu in Fukrey<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"Gained Recognition\\\",\\\"year\\\":[\\\"2010\\\"],\\\"color\\\":[\\\"#C90688\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Ashutosh Gowarikar\\'s Khelein Hum Jee Jaan Sey&quot;]" data-sheets-userformat="[null,null,47617,[null,0],null,null,null,null,null,null,null,null,0,null,[null,2,721024],&quot;sans-serif&quot;,11,null,1]">Ashutosh Gowarikar&#8217;s Khelein Hum Jee Jaan Sey<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"Movie Debut\\\",\\\"year\\\":[\\\"2008\\\"],\\\"color\\\":[\\\"#FFCF00\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Hum Se Jahan&quot;]" data-sheets-userformat="[null,null,513,[null,0],null,null,null,null,null,null,null,null,0]">Hum Se Jahan<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"quote-card\\\",\\\"title\\\":\\\"vishakha singh\\\",\\\"year\\\":null,\\\"color\\\":null,\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;I am not really sophisticated but happy and chilled out&quot;]" data-sheets-userformat="[null,null,14915,[null,0],[null,2,16777215],null,null,null,null,0,null,null,0,null,[null,2,0],&quot;helvetica&quot;,11]">I am not really sophisticated but happy and chilled out<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"}]"
}
{
"_id" : ObjectId("56ea7b9490e2a5b17c143b57"),
"sketchid" : NumberLong(51148),
"tdata" : "[{\\\"type\\\":\\\"dob\\\",\\\"title\\\":\\\"Ali Fazal\\\",\\\"year\\\":null,\\\"color\\\":null,\\\"content\\\":\\\"\\\",\\\"birthdate\\\":[\\\"529718400\\\"],\\\"birthplace\\\":[\\\"Lucknow, Uttar Pradesh\\\"],\\\"zodiac\\\":\\\"Libra\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"Bollywood Appearance\\\",\\\"year\\\":[\\\"2016\\\"],\\\"color\\\":[\\\"#C90688\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Anand L. Rai\\'s Happy Bhaag Jayegi&quot;]" data-sheets-userformat="[null,null,47617,[null,0],null,null,null,null,null,null,null,null,0,null,[null,2,721024],&quot;sans-serif&quot;,11,null,1]">Anand L. Rai&#8217;s Happy Bhaag Jayegi<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"English Movie\\\",\\\"year\\\":[\\\"2015\\\"],\\\"color\\\":[\\\"#FFCF00\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Special Appearance in Furious 7&quot;]" data-sheets-userformat="[null,null,513,[null,0],null,null,null,null,null,null,null,null,0]">Special Appearance in Furious 7<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"First Lead Role\\\",\\\"year\\\":[\\\"2015\\\"],\\\"color\\\":[\\\"#B6D402\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Khamoshiyan&quot;]" data-sheets-userformat="[null,null,513,[null,0],null,null,null,null,null,null,null,null,0]">Khamoshiyan<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"Supporting Role\\\",\\\"year\\\":[\\\"2014\\\"],\\\"color\\\":[\\\"#FF2305\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Bobby Jasoos with Vidya Balan&quot;]" data-sheets-userformat="[null,null,513,[null,0],null,null,null,null,null,null,null,null,0]">Bobby Jasoos with Vidya Balan<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"First Success\\\",\\\"year\\\":[\\\"2013\\\"],\\\"color\\\":[\\\"#85330B\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Fukrey&quot;]" data-sheets-userformat="[null,null,513,[null,0],null,null,null,null,null,null,null,null,0]">Fukrey<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"Bollywood Debut\\\",\\\"year\\\":[\\\"2009\\\"],\\\"color\\\":[\\\"#21C8F5\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Special Appearance in 3 Idiots&quot;]" data-sheets-userformat="[null,null,513,[null,0],null,null,null,null,null,null,null,null,0]">Special Appearance in 3 Idiots<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"American Miniseries\\\",\\\"year\\\":[\\\"2009\\\"],\\\"color\\\":[\\\"#C90688\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Bollywood Hero&quot;]" data-sheets-userformat="[null,null,513,[null,0],null,null,null,null,null,null,null,null,0]">Bollywood Hero<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"timeline\\\",\\\"title\\\":\\\"Screen Debut\\\",\\\"year\\\":[\\\"2008\\\"],\\\"color\\\":[\\\"#FFCF00\\\"],\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;Small role in the English language film The Other End of the Line&quot;]" data-sheets-userformat="[null,null,309761,[null,0],null,null,null,null,null,null,null,null,0,null,[null,2,721024],&quot;sans-serif&quot;,11,null,1,null,null,1]">Small role in the English language film The Other End of the Line<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"},{\\\"type\\\":\\\"quote-card\\\",\\\"title\\\":\\\"Ali Fazal\\\",\\\"year\\\":null,\\\"color\\\":null,\\\"content\\\":\\\"<p><span data-sheets-value="[null,2,&quot;I love being in love.&quot;]" data-sheets-userformat="[null,null,14915,[null,0],[null,2,16777215],null,null,null,null,0,null,null,0,null,[null,2,4144959],&quot;georgia&quot;,11]">I love being in love.<\\\\/span><\\\\/p>\\\\n\\\",\\\"birthdate\\\":null,\\\"birthplace\\\":null,\\\"zodiac\\\":\\\"Capricorn\\\"}]"
}
When I tried following commands I get the following errors
db.timeline.find({tdata:{"birthdate":{$exists: true, “$ne”: null }}},{sketchid})
2016-08-19T12:02:14.665+0530 E QUERY [thread1] SyntaxError: illegal character #(shell):1:53
db.timeline.find({tdata:{"birthdate\\":{$exists: true, “$ne”: null }}},{sketchid})
2016-08-19T12:02:53.357+0530 E QUERY [thread1] SyntaxError: unterminated string literal #(shell):1:25
db.timeline.find({tdata:{\\"birthdate\\":{$exists: true, “$ne”: null }}},{sketchid})
2016-08-19T12:03:06.572+0530 E QUERY [thread1] SyntaxError: illegal character #(shell):1:25

You need to use the positional operator if you want to test only the first element of the tdata array. Also depending on your version {$ne:null} doesn't always give what you'd expect. You can check against the null type 10 instead:
db.timeline.find({"tdata.0.birthdate": {$exists:true,$not : { $type : 10 }} },{sketchid:1})

Related

How to get the highest probability records from the collection. (Show most time searched)

I am creating application where it contains many dropdowns(more than 20), user can select any dropdowns to get the results. Every user login they are selecting dropdowns and get the results.
What I am doing is, storing all the selected dropdown values of each user(basically search string), planning to show your common searches, where they can just copy that search string and get the results.
Dropdown selection is mutiple
Intention is reducing the effort of selecting dropdowns if they have most common/almost common search they have. My dataset looks like below data stored in MongoDB.
This data is for single user, likewise it contains for all users.
{
"UserID": "123",
"SearchData": [
{
"searchText": "Area=[Bengaluru,Mumbai] Street_Number=[123,787] Locality=[Hebala,Electronic City] Branch=India",
"searchDateTime": "2020-04-03"
},
{
"searchText": "Area=Delhi Street_Number=[123,797,753,64] Locality=[Rajbhava,Redfort]",
"searchDateTime": "2020-04-04"
},
{
"searchText": "Region=[Asia,Europe] Branch=[India,Germany] Area=Delhi",
"searchDateTime": "2020-04-02"
},
{
"searchText": "Area=[Bengaluru,Mumbai] Team_name=[Team 1, Team 2] IsNewTeam=1 Region=[Asia,Europe] Branch=India",
"searchDateTime": "2020-03-04"
},
{
"searchText": "Region=United_States Branch=NewYork Team=[Team 1,Team 4] Locality=WTO",
"searchDateTime": "2020-04-04"
}
]
}
Expected Results like:
Your most searched/selected fields and Values are(Results for last 150 days searchText), Because I am planning not to keep Old data
1. Area=[Bengaluru,Mumbai] Branch=India Team 1 // Since this is common in many stings(Ex: Here in two strings)
2. Region=[Asia,Europe]
3. Branch=India
4. Team =Team 1
5. Area=[Bengaluru,Mumbai]
6. IsNewTeam == //If any common match found.
7. Area = //If any other common values found Expect the **Bengaluru,Mumbai**
//Ex : Dehli, Noida. This should come here
Any help would be very much appreciated.
Thanks in advance

Postgres query array elements inside JSON?

I have Postgres 11 table called fb_designs that has a json column with data structured like so:
{
"listings": [
{
"id": "KTyneMdrAhAEKyC9Aylf",
"active": true
},
{
"id": "ZcjK9M4tuwhWWdK8WcfX",
"active": false
}
]
}
and a tags column in a character varying[] format as so {dWLaRWChaThFPH6b3BpA,BrYiPaUiou020hsmRugR}. Both lengths are undefined.
What I am trying to do is produce a some queries that will let me say in laymans terms,
show me all results where at all items.listings has an
active status and tags contains BrYiPaUiou020hsmRugR
I got this far, however I'm not sure how to add in WHERE uid = "foo", WHERE tags contains "foo", "bar and WHERE title is like %hoot%
SELECT id, title, tags, selected_preview_image, items
FROM fb_designs r, json_array_elements(r.items#>'{listings}') obj
WHERE obj->>'active' = 'true'
GROUP BY id
If they are all true, then none of them are false. Sounds like you want to negate the containment operation over false.
select * from fb_designs where
not items::jsonb #> '{"listings":[{"active": false}]}'
and tags && ARRAY['BrYiPaUiou020hsmRugR']::varchar[]

Meteor / Mongo 'findOne' function returning "undefined"

I'm (obiously) a beginner, first post. I'm creating a flashcards project with Meteor. I have a db called "cardsets" that contains lots of documents that look similar to this:
{ "_id" : "asdfg00724",
"setTitle" : "Les animaux",
"vocab" : [
[ "the dog", "le chien" ],
[ "the cat", "le chat" ],
[ "the rabbit", "le lapin" ],
[ "the horse", "le cheval" ] ] }
What I'm trying to do is to access a single document from the collection and assign each field in the document to a variable of the same name, with the 'vocab' field being brought in as an array.
I have an /imports/api/cardsets.js that contains this:
import { Mongo } from 'meteor/mongo';
export const Cardsets = new Mongo.Collection('cardsets');
The /server/main.js includes this line:
import '../imports/api/cardsets.js';
And the /client/main.js file includes this line:
import { Cardsets } from '/imports/api/cardsets.js';
In the /client/main.js file, I am able to directly 'insert' new documents into the database, so I know the Cardfiles const is accessible in main.js:
Cardsets.insert( {language: "Chinese", course: "CHIN102"});
Works as expected. (This is only for testing). However, NOTHING I have done with the "findOne" has produced any results:
var asdf = Cardsets.findOne( { _id : "asdfg00724"});
console.log("asdf = "+asdf);
Produces "asdf = undefined" in the console.
And if I type "Cardsets.find({}).fetch()" in the browser console, I get an error: "Cardsets is not defined."
I've tried this as well:
Cardsets.findOne({ _id : "asdfg00724"}, function(err, document) {
console.log(document.name);
});
But this produces a huge error containing the text "Match error: Failed Match.OneOf, Match.Maybe or Match.Optional validation".
I realize that there's probably a very easy thing I'm missing, but after working on this for many days non-stop, I felt it's time to ask for help.
find() and findOne() do not accept callbacks as parameters, hence your huge error.
your variables (including collections) will not be available in the console unless you're at a breakpoint inside a function where those variables are defined,
most likely you're trying to access Cardsets before the client has received that data from the server via pub-sub. Once you implement actual publications and subscriptions you'll be able to look at the .ready() state of subscriptions to know when your data is available.

Sequelize: where query string is in array of strings postgresql

I am trying to perform a query in sequelize where I want to get only users that have the correct role. Roles are stored as an array of strings. For example ['student'] or ['school_owner', 'admin'].
In this particular case, I'm actually trying to get a school and include the school owners for that school. The failing relevant query is
const ownerQuery: { [key: string]: any } = {};
ownerQuery.roles = {$in: ["{school_owner}"]};
School
.findById(req.params.id,{include: [{ model: User, where: ownerQuery }]})
.then((school: School | null) => {
if (school === null) {
res.status(404).json({message: "Not Found"})
} else {
res.json(school)
}
}, (error) => next(error))
sequelize is storing the array values as something like {school_owner, admin}. The documentation says that I can use the following instead for my $in query
ownerQuery.roles = {$in: ["school_owner"]};
Which removes the {} but it gives me a Array value must start with "{" or dimension information.' error.
In the first example, the query doesn't fail, but it doesn't work like an $in query either. I have to match the contents of roles exactly. For example, if a user has both admin and school_owner roles I have to say
ownerQuery.roles = {$in: ["{school_owner, admin}"]};
What's the correct way to perform an $in query so that I can match all users that have a specific roles?
The correct way to implement this functionality is to do the following
ownerQuery.roles = { $contains: ["school_owner"] };
This will return all users that have a role school_owner in their array of roles

Web Api and & EF 6

I have three successives calls to the same web service to post some comments.
The structure is : {Doc_No is TEXT, Line_No is NUMBER, Description is TEXT}
Comments_doc = [{
Doc_No: 'xx_01',
Description : 'TOTO_1'
},
{
Doc_No: 'xx_01',
Description : 'TOTO_2'
},
{
Doc_No: 'xx_01',
Description : 'TOTO_3'
}]
$.each(Comments_doc, function(aComment){
$.post(...) //here post aComment
});
The primary keys are : Doc_No and Line_No
Line_No is calculated by the web service, it looks for the last one and add one.
The problem is ; looking for the last record is faster than the insert, so at any given time, I have the same Line_No for two differents records !
How could I avoid this ?
thank you for your help.