How to select friends data from the user document.
EG:-
{
"_id" : ObjectId("5a70c1159d0e9b2c40bfbfed"),
"name" : "Mo Salah",
"profile_pic":"(LINK)",
"d":"d",
"id" : "1",
"friends" : [
{
"id" : "2",
"name" : "mike",
"image" : "(LINK)"
},
{
"id" : "3",
"name" : "Sam",
"image" : "(LINK)"
},
{
"id" : "4",
"name" : "John",
"image" : "(LINK)"
}
]
}
I want to search in the users' collection based on the IDs in friends' object/array.
EDIT
Output should be like
{
"_id" : ObjectId("5a70c1159d0e9b2c40bfbmde"),
"name": "mike",
"profile_pic":"(LINK)",
"id" : "2",
"friends":[{array of his friends too}]
}
Related
I want to groupby based on condition where my target field can be sender.category or reciever.category based on condition that either of those field belongs to "cat1", and get the last record of each of on sender.id or reciever.id based on createdAt.
Sample Json1:
{
"code" : "34242342",
"name" : "name1",
"amount" : 200,
"sender" : {
"id" : "fsrfsr3242",
"name" : "name2",
"phone" : "12345678",
"category": "cat1"
},
"receiver" : {
"id" : "42342rewr",
"name" : "naem3",
"phone" : "5653679755",
"category": "cat2"
},
"message" : "",
"status" : "done",
"createdAt" : "2019-09-27T09:17:32.597Z"
}
Sample Json2:
{
"code" : "34242342",
"name" : "name1",
"amount" : 200,
"sender" : {
"id" : "fsrfsr3242",
"name" : "name2",
"phone" : "12345678",
"category": "cat3"
},
"receiver" : {
"id" : "42342rewr",
"name" : "naem3",
"phone" : "5653679755",
"category": "cat1"
},
"message" : "",
"status" : "done",
"createdAt" : "2019-09-27T09:17:32.597Z"
}
Query:
[{$match: {
$or: [{ "sender.category": 'cat1' }, {"receiver.category" : 'cat1'}]
}}, {$sort: {
"createdAt": 1
}}, {$group: {
_id: {sender :"$sender.id", reciever : "$receiver.id"},
lastrecord: {
$last: "$$ROOT"
}
}}]
I want to return only the last record, sender.id or receiver.id can have multiple records of which i only want to retrieve the last one. But my query is returning multiple records.
How to get only the last i.e latest one based on above conditions and createdAt?
Sample output:
{
"lastrecord" : {
"name" : "name1",
"amount" : 1000,
"sender" : {
"name" : "name2",
"phone" : "213232141",
"category" : "cat1"
},
"receiver" : {
"name" : "name",
"phone" : "321312412",
"category" : "cat2"
},
"status" : "done",
"createdAt" : "2019-11-25T17:00:17.226+06:30"
}
}
i want this for every sender.id or receiver.id
My schema for list collection is-
list:
{
username : "some username",
listitem : "some item",
category : "some category",
status : "some status"
}
db.list.find() gets all the results, but I want to retrieve data based on category where the results with same category value appear together.Here is sample output of
db.list.find()
{
"_id" : ObjectId("585669eb4aa058f4e7972db3"),
"username" : "user1",
"listitem" : "item 1",
"status" : "P",
"category" : "A",
}
{
"_id" : ObjectId("5856a7c64aa058f4e7972db4"),
"username" : "user2",
"listitem" : "item 2",
"status" : "p",
"category" : "B",
}
{
"_id" : ObjectId("5858faedde3ffb11a083e770"),
"username" : "user1"
"listitem" : "item 3",
"status" : "p",
"category" : "A",
}
But I want all my 'A' category results together and 'B' category results together.
that is,output should be like this-
{
"_id" : ObjectId("5856a7c64aa058f4e7972db4"),
"username" : "user2",
"listitem" : "item 2",
"status" : "p",
"category" : "B",
}
{
"_id" : ObjectId("585669eb4aa058f4e7972db3"),
"username" : "user1",
"listitem" : "item 1",
"status" : "P",
"category" : "A",
}
{
"_id" : ObjectId("5858faedde3ffb11a083e770"),
"username" : "user1"
"listitem" : "item 3",
"status" : "p",
"category" : "A",
}
Please someone tell me how to do this.Whether this directly possible through mongodb query or I have to perform operations to format output in this form, when I get result in node js server?
It is a simple use case of sort
db.list.find().sort( { category: 1 } )
All the docs will be sorted by the corresponding category values and hence, all docs with the same category value will be listed together.
I have below document structure.
{
"_id" : { "teacherId" : "<teacherId>", "Year" : "<Year>" },
"groups" : [ {
"groupId" : "<uuid>",
"groupName" : "<name>",
"groupNameLowerCase" : "<name_in_lower_case>",
"description" : "<desc>",
"students" : ["<studentid1>", "<studentid2>", ...],
"editedDate" : "<currentTimestamp>"
},
...
],
"editedDate" : "<currentTimestamp>",
"points" : "<points>"
}
Consider that below two documents are present in DB
{
"_id" : { "teacherId" : "1", "Year" : "2016" },
"groups" : [ {
"groupId" : "123",
"groupName" : "Test1",
"groupNameLowerCase" : "test1",
"description" : "sample document",
"students" : ["11", "22"]
},
{
"groupId" : "234",
"groupName" : "Test2",
"groupNameLowerCase" : "test2",
"description" : "sample document",
"students" : ["11", "22"]
},
{
"groupId" : "345",
"groupName" : "Test3",
"groupNameLowerCase" : "test3",
"description" : "sample document",
"students" : ["21", "32"]
}
],
"points" : "650"
}
{
"_id" : { "teacherId" : "1", "Year" : "2015" },
"groups" : [ {
"groupId" : "123",
"groupName" : "HOCKEY",
"groupNameLowerCase" : "HOCKEY",
"description" : "HOCKEY team",
"students" : ["11", "22"]
},
{
"groupId" : "234",
"groupName" : "football",
"groupNameLowerCase" : "football",
"description" : "sample football",
"students" : ["11", "22"]
},
{
"groupId" : "345",
"groupName" : "Test3",
"groupNameLowerCase" : "test3",
"description" : "sample document",
"students" : ["21", "32"]
}
],
"points" : "650"
I want to select groups for the specified student and teacher combination. e.g. If I supply teacherid= 1 and student id =11 then query should return two documents with matching groups. I wrote below code to get the matching groups in document. But afterward I understand that elemMatch will only return first element matching. It will return two documents but with only one group in it.
Here I would like to understand the options available in Mongodb 2.4 to filter arrays in document returned by some query.
String teacherId = "1";
String studentId = "11";
Criteria documentSearchCriteria = where("_id.teacherId").is(teacherId)
.and("groups")
.elemMatch(where("students").in(studentId));
Criteria groupFilterCriteria = where("groups").elemMatch(where("students").in(studentBid));
BasicQuery query = new BasicQuery(documentSearchCriteria.getCriteriaObject(), groupFilterCriteria.getCriteriaObject());
List<GroupsDocument> groupsDocumentList = groupsMongoTemplate.find(query, GroupsDocument.class);
As you said elemMatch will retrieve only first object in an array so you have to use aggregate future to achieve your output
MatchOperation match = Aggregation.match(Criteria.where("_id.teacherId").is("1").and("groups.students").in(11));
UnwindOperation unwind = Aggregation.unwind("groups");
GroupOperation group = Aggregation.group("_id").push("groups").as("groups").first("points").as("points");
Aggregation aggregation = Aggregation.newAggregation(unwind, match, group);
AggregationResults<BasicDBObject> groupResults = mongoTemplate.aggregate(aggregation,
CustomGroupsDocument.class, BasicDBObject.class);
List<BasicDBObject> result = groupResults.getMappedResults();
I am new to MongoDB. And I have following collections in my MongoDB. My Problem is I am not able to make a find command which gives required facilities based on provided ID or Name.
Find command which I have tried BUT NOT working :-
db.mgh_facilities.find({facilities: {$elemMatch: {name: "Foreign exchange assistance"}}}).
For me its returning all the records. Shouldn't it be just returning { "id" : "11", "name" : "Foreign exchange assistance" }
My Collections:-
{
"_id" : ObjectId("548acc28ae6ff1c0fd1d7470"),
"responseCode" : "true",
"facilities" : [
{
"id" : "11",
"name" : "Foreign exchange assistance"
},
{
"id" : "12",
"name" : "Assistance with luggage on request"
},
{
"id" : "13",
"name" : "24 hours power back-up"
},
{
"id" : "14",
"name" : "A/C Power Backup Available"
},
{
"id" : "15",
"name" : "swimming pool"
},
{
"id" : "35",
"name" : "shoe cleaning service"
},
{
"id" : "36",
"name" : "Smoke detectors"
},
{
"id" : "37",
"name" : "Fire Extinguishers in each room"
},
{
"id" : "38",
"name" : "Pest Control"
},
{
"id" : "39",
"name" : "Conference / Banquet Hall"
},
{
"id" : "45",
"name" : "Restaurant"
},
{
"id" : "53",
"name" : "Anti-slip ramps"
},
{
"id" : "56",
"name" : "Tea/ Coffee Maker in the Rooms"
},
{
"id" : "59",
"name" : "Wi Fi Internet"
}
]
}
The find command has found the document which contains the facility object with a name matching your search. It doesn't know that you only want to see the single subdocument responsible for that document matching your search criteria.
You can tell mongo that you want to see that element with the positional $ operator.
db.mgh_facilities.find({"facilities.name": "Foreign exchange assistance"}, {"facilities.$": true})
You can try this
db.mgh_facilities.aggregate([
{
$unwind:"$facilities"
},
{
$match:{"facilities.name": "Foreign exchange assistance"}
},{
$project:{
_id:0,
facilities:1
}
}
])
result:
{
"result" : [
{
"facilities" : {
"id" : "11",
"name" : "Foreign exchange assistance"
}
}
],
"ok" : 1
}
Say we have the following collection of documents:
{ "_id" : ObjectId("50a69fa904c8310609600be3"), "id" : 100, "city" : "San Francisco", "friends" : [ { "id" : 1, "name" : "John" }, { "id" : 2, "name" : "Betty" }, { "id" : 3, "name" : "Harry" } ] }
{ "_id" : ObjectId("50a69fc104c8310609600be4"), "id" : 200, "city" : "Palo Alto", "friends" : [ { "id" : 1, "name" : "Carol" }, { "id" : 2, "name" : "Frank" }, { "id" : 3, "name" : "Norman" } ] }
{ "_id" : ObjectId("50a69fc304c8310609600be5"), "id" : 300, "city" : "Los Angeles", "friends" : [ { "id" : 1, "name" : "Fred" }, { "id" : 2, "name" : "Neal" }, { "id" : 3, "name" : "David" } ] }
.
.
.
Now let's say that Frank (Palo Alto, id=2) is no longer my friend, and I want to delete him from the collection. I thought the following might work, but it doesn't:
db.test.update({"city":"Palo Alto"},{"$pull":{"friends.name":"Frank"}})
I'd like to be able to do something like that. Delete an object within an array within a collection of documents. How do you do this?
You were close. The query should be like this:
db.test.update({"city":"Palo Alto"},{"$pull":{"friends":{"name":"Frank"}}});
$pull takes an object whose field specifies the field array "friends". The value {"name":"Frank"} represents the query (to run inside the array) to find the element to pull out.