MongoDB .find() only ObjectId's embedded in an Array. - javascript

I am trying to get only the ObjectId's from One specific Document that is embedded in the projects Array.
Basically I am trying to make a database that will have users and each user will have there own projects.
Thank you !
db.users.find().pretty()
{
"_id" : ObjectId("5762c0cf2b9a78006373a684"),
"name" : "seq",
"pass" : "seq",
"projects" : [
{
"pid" : ObjectId("5762c0ba2b9a78006373a682"),
"name" : "aaa"
},
{
"pid" : ObjectId("5762c0ba2b9a78006373a683"),
"name" : "bbb"
}
]
}
{
"_id" : ObjectId("5762c28d2b9a78006373a687"),
"name" : "leq",
"pass" : "leq",
"projects" : [
{
"pid" : ObjectId("5762c2892b9a78006373a685"),
"name" : "ccc"
},
{
"pid" : ObjectId("5762c2892b9a78006373a686"),
"name" : "ddd"
}
]
}

let say we want two pids
{"pid" : ObjectId("5762c0ba2b9a78006373a682")} and
{"pid" : ObjectId("5762c2892b9a78006373a686"),}
and only inner documents
so required response should look like:
{
"_id" : ObjectId("5762c0ba2b9a78006373a682"),
"name" : "aaa"
},{
"_id" : ObjectId("5762c2892b9a78006373a686"),
"name" : "ddd"
}
Aggregation framework can manipulate documents, match only needed ones and transform inner structure by project phase:
var match = {
$match : {
"projects.pid" : {
$in : [ObjectId("5762c0ba2b9a78006373a682"),
ObjectId("5762c2892b9a78006373a686")]
}
}
}
var unwind = {
$unwind : "$projects"
};
// now move array objet as top level object
var project = {
$project : {
_id : "$projects.pid",
name : "$projects.name",
// list other fields here
}
}
db.vic.aggregate([match, unwind, match, project])

Related

change only one field of entire array of embedded document in mongoose

i have a list schema and a question set schema. the quetsionSet schema is embedded inside the list schema. its working fine but how can i update anything inside the array of embedded document i.e. here i want to change the listname of all the documents inside questionSet (array of questionSet documents).
here is an example of my list document model
{ "_id" : ObjectId("60f2cc07275bbb30d8cb268e"),
"listName" : "dsa",
"aboutList" : "dsa queestions",
questionSet" : [ { "solved" : false,
"_id" : ObjectId("60f2cc12275bbb30d8cb2695"),
"topic" : "array",
"name" : "array is best",
"url" : "www.arr.com",
"listname" : "dsa",
"__v" : 0 },
{ "solved" : false,
"_id" : ObjectId("60f2cc1b275bbb30d8cb269d"),
"topic" : "linked list",
"name" : "reverse list",
"url" : "www.list.com",
"listname" : "dsa",
"__v" : 0 }
],
"__v" : 2
}
you can use the following in your case
db.<collection_name>.updateOne(
{ "_id" : ObjectId("60f2cc07275bbb30d8cb268e")},
{
$set: {
'questionSet.$[].listname': "javascript"
}
}
)

How to extract data from Firebase realtime database JSON-export

I have a Firebase realtime-database export-json that has nested informations, that I would like to extract. The structure of the JSON looks like this:
{
"users" : {
"024w97mv8NftGFY8THfQIU6PhaJ3" : {
"email" : "xxx",
"id" : "024w97mv8NftGFY8THfQIU6PhaJ3",
"name" : "xxx",
"items" : {
"-LQL9n-r9BGdo3HJZ2sk" : {
"disliked" : true,
"id" : 396,
"name" : "Aaa"
},
"-LQL9oO63nH-QW2w6zz0" : {
"liked" : true,
"id" : 3674,
"name" : "Bbb"
}
}
},
"0ERLT5DLRvbZUnjlnM7Ow0qItpz2" : {
"email" : "zzz",
"id" : "0ERLT5DLRvbZUnjlnM7Ow0qItpz2",
"name" : "zzz",
"items" : {
"-LIZnriSVQMzqTsPFNYa" : {
"id" : 396,
"liked" : true,
"name" : "Aaa"
},
"-LIZnrzOuk4WyjqEiLG8" : {
"disliked" : true,
"id" : 4805,
"name" : "Ccc"
}
}
}
}
}
What I need to achieve is getting a list of all liked item-names, and ideally counting how often an item is liked.
Is there a simple tool or script to do that? Ruby or Javascript would be preferred. Thanks a lot!
You can parse your JSON data in ruby like below
result_hash = JSON.parse(result)
result_ary = result_hash["users"].collect do |k,v|
v["items"].values.select{|v1| v1["liked"] == true }
end
result_data = result_ary.flatten
result of parsing
=> [{"liked"=>true, "id"=>3674, "name"=>"Bbb"}, {"id"=>396, "liked"=>true, "name"=>"Aaa"}]
Now its very easy for getting your required result
result_data.collect{|x| x["name"] }
=> ["Bbb", "Aaa"]
result_data.count {|x| x["name"] == "Aaa"}
=> 1
result_data.count {|x| x["name"] == "Bbb"}
=> 1

MongoDB - Query nested objects in nested array

I'm kindly requesting your help for this query that I need to do and I'm not very proficient yet in MongoDB. My data structure looks like this:
db.getCollection('EventDateValidation').find({}):
/* 1 */
{
"_id" : ObjectId("5b7b2e3ae5e2100007717d81"),
"_class" : "com.overwatch.common.model.EventDateValidation",
"caseNo" : "OW000002269122201810201135",
"loanNo" : "000002269122",
"eventType" : "BREACLETTR",
"validationStepData" : [
{
"startDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Mahalakshmi M",
"auditedDate" : "2018-12-12"
}
},
{
"completedDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Mahalakshmi M",
"auditedDate" : "2018-12-13"
}
},
{
"deadlineDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Mahalakshmi M",
"auditedDate" : "2018-12-13"
}
}
]
}
/* 2 */
{
"_id" : ObjectId("5b7c11095c2b4d0007bc8c54"),
"_class" : "com.overwatch.common.model.EventDateValidation",
"caseNo" : "OW000000854076201808181158",
"loanNo" : "000000854076",
"eventType" : "FORSALAPPR",
"validationStepData" : [
{
"startDate" : {
"comments" : ""
}
},
{
"completedDate" : {
"comments" : "Received Date = 8/4/2017"
}
},
{
"deadlineDate" : {
"comments" : ""
}
}
]
}
/* 3 */
{
"_id" : ObjectId("5b7ad05d5c2b4d0007bc8631"),
"_class" : "com.overwatch.common.model.EventDateValidation",
"caseNo" : "OW000000873954201810201235",
"loanNo" : "000000873954",
"eventType" : "HUDNOTIFCA",
"validationStepData" : [
{
"startDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Brett Scott",
"auditedDate" : "2018-09-25"
}
},
{
"completedDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Brett Scott",
"auditedDate" : "2018-09-25"
}
},
{
"deadlineDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Brett Scott",
"auditedDate" : "2018-09-25"
}
}
]
}
From this collection, I need to find the documents that have an "auditedDate" in the "deadlineDate". In this example, I would find the documents 1 and 3. Please help me as I'm stuck on this one.
I have tried
db.getCollection('EventDateValidation').find({"validationStepData.deadlineDate.auditedDate":{$exists:true}})
But doesn't seem to work. Help please!
Just for clearing things up: the query in the question works well. I chatted with #Gabriel, and the problem was that Robomongo added hidden non-printable unicode characters to the query.
All in all, for any interested nomads, here are few ways to query an array of objects:
1) Implicit $elemMatch / simple dot notation on an array:
db.getCollection('EventDateValidation').find({"validationStepData.deadlineDate.auditedDate": {$exists:true}})
2) Explicit $elemMatch (we can have multiple query criteria):
db.getCollection('EventDateValidation').find({"validationStepData": { $elemMatch: {"deadlineDate.auditedDate" : {$exists:true} }}})
3) Array dot notation with an index position (when we know the exact position of an element inside an array):
db.getCollection('EventDateValidation').find({"validationStepData.2.deadlineDate.auditedDate": {$exists:true}})
Dot notation wouldn't work since you have an array of objects within validationStepData. You could use $elemMatch to apply your query conditions to the array elements that match your expression.
db.getCollection('EventDateValidation').find({"validationStepData" : { $elemMatch: {"deadlineDate.auditedDate" : {$exists:true} }}})

How to match and find between an array and documents in mongoDB

I have an array of IDs like for example
[id1,id2,id3,......]
and i have a collection with documents for example
{
"_id" : ObjectId("1111111111111"),
"phoneNumber" : "1234567891",
"fid" : "id1",
"pid" : "abcd",
"activeFlag" : true
},
{
"_id" : ObjectId("2222222222"),
"phoneNumber" : "1234567891",
"fid" : "id1",
"pid" : "efgh",
"activeFlag" : true
},
{
"_id" : ObjectId("33333333333"),
"phoneNumber" : "1234567891",
"fid" : "id2",
"pid" : "xyz",
"activeFlag" : true
},
{
"_id" : ObjectId("4444444444444"),
"phoneNumber" : "1234567891",
"fid" : "id3",
"pid" : "mnop",
"activeFlag" : true
}
i want to find the documents with fid which match IDs in my array of IDs ,
also i want to sort it according to _id and limit is 9.
if id1 taken then i need all documents which is having fid as id1, like that.
This script should do the trick
var listId = ["id1", "id2", "id3"];
var cursor = db.collection.find({fid: {$in: listId}}).sort({_id: 1}).limit(9);
// iterate over documents
if (cursor != null && cursor.hasNext()){
while (cursor.hasNext()){
// print documents
print(JSON.stringify(cursor.next()));
}
}
to run it, create a file names script.js, copy the code above inside it and then run the command
mongo databaseName < script.js

How to lazy load with angular using mongodb data

I want to implement lazy loading in angular.js, i am sending the list of data from backend to the UI using nodejs, i need to implement, on scroll 10 items, are there any examples to achieve this please share any links to do this. Please can anybody help me on this.
Lazy loading is nothing to do with DB, since it depends on the DAO layer, whereas DB is concerned about returning the data for the query submitted to it.
My approach to achieve lazy loading from UI
Using pagination we can do lazy loading
1) Find the total number of documents in your collection
2) Each time when you are loading the page with next set of data, pass on the required information such as from which document the DB needs to send the data
3) Repeat step 2 until you reach the total number of documents in your collection
An example Let us have a collection with few records
db.mycollection.find();
{ "_id" : ObjectId("58947e7e93cbb73057657d60"), "name" : "Clement" }
{ "_id" : ObjectId("58947e7e93cbb73057657d61"), "name" : "Rockin" }
{ "_id" : ObjectId("58947e7e93cbb73057657d62"), "name" : "Gowri" }
{ "_id" : ObjectId("58947e7e93cbb73057657d63"), "name" : "Inbaraj" }
{ "_id" : ObjectId("58947e7e93cbb73057657d64"), "name" : "Siva" }
{ "_id" : ObjectId("58947e7e93cbb73057657d65"), "name" : "Rani" }
{ "_id" : ObjectId("58947e7e93cbb73057657d66"), "name" : "Rose" }
{ "_id" : ObjectId("58947e7e93cbb73057657d67"), "name" : "Rekha" }
{ "_id" : ObjectId("58947e7e93cbb73057657d68"), "name" : "Dev" }
{ "_id" : ObjectId("58947f6f93cbb73057657d69"), "name" : "Joe" }
{ "_id" : ObjectId("58947f8393cbb73057657d6a"), "name" : "Beniton" }
Prerequisite for doing pagination
db.mycollection.find().count()
11
Let me have the initial load size as 5
My first query to DB would be
db.mycollection.find().sort({"_id":1}).limit(5);
{ "_id" : ObjectId("58947e7e93cbb73057657d60"), "name" : "Clement" }
{ "_id" : ObjectId("58947e7e93cbb73057657d61"), "name" : "Rockin" }
{ "_id" : ObjectId("58947e7e93cbb73057657d62"), "name" : "Gowri" }
{ "_id" : ObjectId("58947e7e93cbb73057657d63"), "name" : "Inbaraj" }
{ "_id" : ObjectId("58947e7e93cbb73057657d64"), "name" : "Siva" }
My Next query to DB
db.mycollection.find().sort({"_id":1}).skip(5).limit(5);
{ "_id" : ObjectId("58947e7e93cbb73057657d65"), "name" : "Rani" }
{ "_id" : ObjectId("58947e7e93cbb73057657d66"), "name" : "Rose" }
{ "_id" : ObjectId("58947e7e93cbb73057657d67"), "name" : "Rekha" }
{ "_id" : ObjectId("58947e7e93cbb73057657d68"), "name" : "Dev" }
{ "_id" : ObjectId("58947f6f93cbb73057657d69"), "name" : "Joe" }
final query would be
db.mycollection.find().sort({"_id":1}).skip(10).limit(5);
{ "_id" : ObjectId("58947f8393cbb73057657d6a"), "name" : "Beniton" }
In this example,
Sort on _id is used, which is based on insertion time, which helps us in ordering the documents and render it for the subsequent queries.
Hope it Helps!
References:
https://www.mongodb.com/blog/post/the-mean-stack-mongodb-expressjs-angularjs-and
Lazy Loading/More Data Scroll in Mongoose/Nodejs
http://adrichman.github.io/implementing-a-lazy-load-and-infinite-scroll-in-angularjs/

Categories