update nth document in a nested array document in mongodb - arrays

I need to update a document in an array inside another document in Mongo DB
{
"_id" : ObjectId("51cff693d342704b5047e6d8"),
"author" : "test",
"body" : "sdfkj dsfhk asdfjad ",
"comments" : [
{
"author" : "test",
"body" : "sdfkjdj\r\nasdjgkfdfj",
"email" : "test#tes.com"
},
{
"author" : "hola",
"body" : "sdfl\r\nhola \r\nwork here"
}
],
"date" : ISODate("2013-06-30T09:12:51.629Z"),
"permalink" : "jaiho",
"tags" : [
"jaiho"
],
"title" : "JAiHo"
}
Q1) Update email of 0th element of comments array
db.posts.update({"permalink" : "haha"},{$set:{"comments.0.email":1}})
This doesn't throw any exception but doesn't update anything as well
Q2) Add a field on nth element of comments array number_likes
db.posts.update({"permalink" : "haha"},{$inc:{"comments.0.num_likes":1}})
Doesn't work either.
Am I missing something here?

Q1: If you update with permalink 'jaiho' instead of 'haha', it most certainly updates the email;
> db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}})
> db.posts.find()
..., "email" : 1 },...
Q2: Same goes for this include;
> db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}})
> db.posts.find()
..., "num_likes" : 1 },...

If you are trying to do it dynamically in Node JS following should work.
i = 0;
selector = {};
operator = {};
selector['comments.' + i + '.email'] = 1; // {'comments.0.num_likes' : 1}
operator['$inc'] = selector; // {'$inc' : {'comments.0.num_likes' : 1} }
db.posts.update({'permalink' : 'xyz'}, operator);

Related

Arabic text in swift

i have array of objects like this
"sub-specialty" : [
{
"id" : 1,
"title" : "Adult Physiotherapy",
"ar_title" : "علاج طبيعي بالغين",
"name" : "علاج طبيعي بالغين"
},
{
"id" : 2,
"title" : "Pediatric Physiotherapy",
"ar_title" : "علاج طبيعي اطفال",
"name" : "علاج طبيعي اطفال"
},
{
"id" : 3,
"title" : "Sport Injuries",
"ar_title" : "اصابات ملاعب",
"name" : "اصابات ملاعب"
},
{
"id" : 4,
"title" : "Rehabilitation",
"ar_title" : "تأهيل",
"name" : "تأهيل"
}
]
when i use map to grab name only like this
let sub = sub-specialty.map({($0.name ?? "")}).joined(separator: ", ") ?? ""
i got rubbish characters or text is flipped please see the attached image
enter image description here
You need to get the text as String and set wherever you want to set. It will work fine. I have worked with multi languages and this work for me.

Find element inside array and return only array

I'm new to MongoDB, so i'm having some newbie problems.
I have this document on DB
{
"_id" : ObjectId("5a7ba73dbf27878474ac7682"),
"Enterprise" : "SpaceX",
"Address" : "qwerty",
"users" : [
{
"name" : "Elon",
"number" : "123456",
"email" : "elon#mars.com",
"user" : "elon",
"pass" : "byeroadster"
},
{
"name" : "Larry",
"number" : "3215465",
"email" : "larry#google.com",
"user" : "larry",
"pass" : "googlepassword"
}
]
}
And i'm doing this query
var db = client.db('hauz_manager');
var findUser = db.collection('system_enterprise');
findUser.find({'users.user': data.user},{contatos: 1}).toArray(function(err, result){
console.log(result.users);
});
With that, i'm having like
Enterprise: "SpaceX"
...
users: [{Object}]
And, i'm not able to do some result.users, returns undefined.
tnx.
console.log(result.users)
I think your callback return array.
You should check callback.
Do you need a loop?

How to retrieve data from mongodb using scala

I have connected to mongodb and filter data like this:
val coll = mongoDB.getTable(db, "report")
val query = new BasicDBObject()
query.put("version",getVersion)
val fields = new BasicDBObject()
fields.put("version",1)
fields.put("project",1)
fields.put("uri",1)
fields.put("test",1)
fields.put("browser",1)
val cursor = coll.find(queryObject,fields)
then get a document like this:
{
"_id" : ObjectId("5a968c6cffac6135b09d6cd5"),
"project" : "com.sink.www.helper",
"uri" : "com.sink.www.helper.somketest",
"browser" : "firefox",
"develop" : "scala",
"duration" : "0.61",
"test" : "acceptance"
"version" : "1.0"
"try" : 1
}
{
"_id" : ObjectId("5a968daaffacc7195c2f9b6i"),
"project" : "com.sink.www.helper",
"uri" : "com.sink.www.helper.somketest",
"browser" : "firefox",
"develop" : "scala",
"duration" : "0.62",
"test" : "acceptance"
"version" : "1.0"
"try" : 1
}
{
"_id" : ObjectId("5a968ea5fface1a723ffr246"),
"project" : "com.sink.www.helper",
"uri" : "com.sink.www.helper.somketest",
"browser" : "chrome",
"develop" : "scala",
"duration" : "0.58",
"test" : "acceptance"
"version" : "1.0"
"try" : 1
}
.....
My question is when "version" is specific value like '1.0', then the field try=try + 1, I have write code like this but this will read mongodb every time, this will cost much time:
while (cursor.hasNext())
{
val details = cursor.next()
if (details.get("version").toString() == getVersion && details.get("browser").toString() == getBrowser)
{
try += 1
}
}
because there are much data in mongodb, so it's not adapt to our project. so I want to get specific data to array or others and get to judge then let try+1, I write code like this but report error:
val scenarioArray = coll.find(queryObject,fields).toArray
for (i <- 0 to scenarioArray.length - 1)
{
println(scenarioArray(i))
}
error: value length is not a member of java.util.List[com.mongodb.DBObject]
error: java.util.List[com.mongodb.DBObject] does not take parameters
I don't know how to retrieve the document to array or list or others container, could anyone get to help on this? Thanks.

AngularFire, access deep child links?

Using latest Angular with Firebase and I'm trying to access somewhat deep nested items from logged in users.
The structure looks something like this:
firebase -> users -> user-uid -> email/name/pass/lists/ (where lists have) -> list-uid -> item-uid -> item-name.
I want to access that last name-child (preferably through an ng-repeat since they're list items and I want them displayed on each users dashboard).
I've been trying different methods but the closest one are this:
$scope.user = $firebaseObject(ref.child('users').child(authData.uid));
And then in my html (for now):
<span>{{user.lists}}</span>
Which prints out something like: {"-uid":{"age":"21", "name":"martin"},{"-uid":{"age":"25", "name":"john"}}} etc etc etc.
The ref goes to:
var ref = new Firebase('https://url.firebaseio.com');
Any ideas? Thanks!
Edit:
I tried to add a ng-repeat like this:
<li ng-repeat="list in user.lists">{{list.name}}</li>
Which somewhat works, it shows me the objects I've put in which are static but not the ones "one level deeper"...
Edit 2:
Updated with .json for structure.
I can get the "me" out of name but not "mjölk" which are a level deeper:
"users" : {
"8a6da12a-0992-43f5-bb33-95ddd49fed8c" : {
"email" : "torsten#gmail.com",
"lists" : {
"-KDjNYC8GS2QFHYyp74L" : {
"age" : "other",
"name" : "me"
},
"8a6da12a-0992-43f5-bb33-95ddd49fed8c" : {
"-KDjN_NkTQmj_1R00xZL" : {
"done" : false,
"id" : 1458936351305,
"name" : "mjölk"
},
"-KDjN_r0WmT6xiZwadO5" : {
"done" : false,
"id" : 1458936351305,
"name" : "ägg"
},
"-KDjNagkBWmJRj6oQqc2" : {
"done" : false,
"id" : 1458936351305,
"name" : "rejv"
},
"-KDjNb5Fpak_9A_rvn8W" : {
"done" : false,
"id" : 1458936351305,
"name" : "kossor"
},
"-KDjOVtAFJoYVNUkapNC" : {
"done" : false,
"id" : 1458936351305,
"name" : "piss"
},
"-KDjOlemXR2eOoqPBh0v" : {
"done" : false,
"id" : 1458936677873,
"name" : "mjölk igen"
}
}
},
As I said in my comment already: part of your problem is caused by the fact that you are nesting lists. There are many reasons why the Firebase documentation recommends to nest data sparingly and this is one of them.
To unnest the data, you store the user profiles separately from the lists for each user:
"users" : {
"8a6da12a-0992-43f5-bb33-95ddd49fed8c" : {
"email" : "torsten#gmail.com",
}
},
"user_lists" : {
"-KDjNYC8GS2QFHYyp74L" : {
"age" : "other",
"name" : "me"
},
"8a6da12a-0992-43f5-bb33-95ddd49fed8c" : {
"-KDjN_NkTQmj_1R00xZL" : {
"done" : false,
"id" : 1458936351305,
"name" : "mjölk"
},
"-KDjN_r0WmT6xiZwadO5" : {
"done" : false,
"id" : 1458936351305,
"name" : "ägg"
},
"-KDjNagkBWmJRj6oQqc2" : {
"done" : false,
"id" : 1458936351305,
"name" : "rejv"
},
"-KDjNb5Fpak_9A_rvn8W" : {
"done" : false,
"id" : 1458936351305,
"name" : "kossor"
}
}
}
Now if you want to show a list of profile and the lists for the current user, you:
var ref = new Firebase('https://yours.firebaseio.com');
$scope.users = $firebaseArray(ref.child('users'));
$scope.lists = $firebaseArray(ref.child('user_lists').child(auth.uid));
And then in your HTML:
<p>Users:</p>
<ul>
<li ng-repeat="user in users">{{user.email}}</li>
</ul>
<p>Lists for you:</p>
<ul>
<li ng-repeat="list in lists">{{list.name}}</li>
</ul>

how to do custom filter in angular JS and what should be the return type

I am using MEAN stack and trying to filter the data from the ng-repeat.
Here goes my HTML code
<section data-ng-controller="BookingsController" data-ng-init="find()">
<div data-ng-repeat="x in bookings|filter:select_booking" data-ng-href="#!/bookings/{{booking._id}}" class="list-group-item">
<label>Booking ID :</label>{{x.booking_id}}
<label>Membership ID :</label>{{x.membership_id}}
<label>Check Out Date :</label>{{ x.checkout_time | date : "longDate" }}
<label>Rooms :</label><span ng-repeat="room in booking.room_id">{{room}} </span>
<button class="pull-right" value="Block" ng-click="checkout(x)">Check Out</button>
<button class="pull-right" style="margin-right:10px" value="Block" ng-click="services(x)">Add Services</button>
<br>
</div>
</section>
My filter name in the above code is select_booking.
The code for ng-controller goes here
$scope.checkindetails = CheckinDetails.query();/*accessing the mongo db values*/
$scope.select_booking = function (a) {
var f = 0;
jQuery.each($scope.checkindetails, function (key, val) {
if (val.booking_id == a.booking_id) {
console.log("in if");
console.log(a.booking_id);
return true;
}
});
};
My Console.log result:
bookings.client.controller.js:300in if
bookings.client.controller.js:301 ASHISH_BOOK_002
bookings.client.controller.js:300 in if
bookings.client.controller.js:301 ASHISH_BOOK_000
bookings db:here referred as a
{
"_id" : ObjectId("54f02f7ba3c39d8c106bd3f7"),
"user" : ObjectId("54eede3363b3e60c2133fe06"),
"created" : ISODate("2015-02-27T08:48:59.890Z"),
"date_of_cancellation" : "",
"cancelled" : "No",
"points" : 0,
"booking_id" : "ASHISH_BOOK_000",
"checked_out" : "Yes",
"booking_date" : ISODate("2015-02-27T08:48:59.890Z"
"adult_count" : 4,
"room_id" : [
"101",
"102"
],
"rooms_count" : 2,
"resort_id" : "ASH_RESORT001",
"checkout_time" : "2015-02-28T18:30:00.000Z",
"checkin_time" : "2015-02-26T18:30:00.000Z",
"guest" : "no",
"membership_id" : "4",
"__v" : 0
}
{
"_id" : ObjectId("54f560e2e0d3bed8069214f5"),
"user" : ObjectId("54ec4eb13d50decc1f5307b4"),
"created" : ISODate("2015-03-03T07:21:06.386Z"),
"date_of_cancellation" : "",
"cancelled" : "No",
"points" : 0,
"booking_id" : "ASHISH_BOOK_001",
"checked_out" : "Yes",
"booking_date" : ISODate("2015-03-03T07:21:06.386Z"
"adult_count" : 4,
"room_id" : [
"100",
"101"
],
"rooms_count" : 2,
"resort_id" : "ASH_RESORT002",
"checkout_time" : "2015-03-03T18:30:00.000Z",
"checkin_time" : "2015-03-02T18:30:00.000Z",
"guest" : "no",
"membership_id" : "1",
"__v" : 0
}
{
"_id" : ObjectId("54f6942195002c140700dac0"),
"user" : ObjectId("54ec4eb13d50decc1f5307b4"),
"created" : ISODate("2015-03-04T05:12:01.211Z"),
"date_of_cancellation" : "",
"cancelled" : "No",
"points" : 0,
"booking_id" : "ASHISH_BOOK_002",
"checked_out" : "Yes",
"booking_date" : ISODate("2015-03-04T05:12:01.211Z"
"adult_count" : 2,
"room_id" : [
"103"
],
"rooms_count" : 1,
"resort_id" : "ASH_RESORT001",
"checkout_time" : "2015-03-04T18:30:00.000Z",
"checkin_time" : "2015-03-03T18:30:00.000Z",
"guest" : "no",
"membership_id" : "1",
"__v" : 0
}
checkindetails db:
{
"_id" : ObjectId("54f06257d75533c01add0cf0"),
"user" : ObjectId("54ec4eb13d50decc1f5307b4"),
"created" : ISODate("2015-02-27T12:25:59.185Z"),
"id_proof_type" : "abcd",
"address" : "bangalore",
"guest_name" : "Harshavardhan",
"booking_id" : "ASHISH_BOOK_000",
"__v" : 0
}
{
"_id" : ObjectId("54f696b095002c140700dac4"),
"user" : ObjectId("54ec4eb13d50decc1f5307b4"),
"created" : ISODate("2015-03-04T05:22:56.498Z"),
"id_proof_type" : "okoko",
"address" : "okoko",
"guest_name" : "kok",
"booking_id" : "ASHISH_BOOK_002",
"__v" : 0
}
I am able to reach till console.log(a.booking_id);
Here I am comparing the booking_id of a(input parameter) with the booking_id of checkindetails and I want the result value of matching booking_id.
The console.log is providing me the correct answer but when I return that console.log value I am getting a blank answer.
Please Help me to find the correct One.
Thanks in advance.
According to Angularjs documentation a filter:
Selects a subset of items from array and returns it as a new array.
Think of the filter as a subset of your original data, that subset is defined within the function that is called when you use that filter.
So in your example you would define your filter "select_booking" to return the filtered values. They can be partial matches by default, or exact matches by adding.."...:true" to the end.
If you want to match the id, you should return the actual id, not "true".
return a.booking_id;
If your filter returns a single id, your ng-repeat will show all bookings with that id. As a side note, if it is an "id" I would use the exact match like...
"book in bookings|filter:{id:select_booking}:true"
That would be how to set it up. Your return type is what you are filtering. If I'm filtering an array of numbers I return numbers. If I'm filtering text, I return text ect.

Resources