I have two collections. The first collection contains students:
{ "_id" : ObjectId("51780f796ec4051a536015cf"), "name" : "John" }
{ "_id" : ObjectId("51780f796ec4051a536015d0"), "name" : "Sam" }
{ "_id" : ObjectId("51780f796ec4051a536015d1"), "name" : "Chris" }
{ "_id" : ObjectId("51780f796ec4051a536015d2"), "name" : "Joe" }
The second collection contains courses:
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc4"),
"name" : "CS 101",
"students" : [
ObjectId("51780f796ec4051a536015cf"),
ObjectId("51780f796ec4051a536015d0"),
ObjectId("51780f796ec4051a536015d2")
]
}
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc5"),
"name" : "Literature",
"students" : [
ObjectId("51780f796ec4051a536015d0"),
ObjectId("51780f796ec4051a536015d0"),
ObjectId("51780f796ec4051a536015d2")
]
}
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
"name" : "Physics",
"students" : [
ObjectId("51780f796ec4051a536015cf"),
ObjectId("51780f796ec4051a536015d0")
]
}
Each course document contains students array which has a list of students registered for the course. When a student views a course on a web page he needs to see if he has already registered for the course or not. In order to do that, when the courses collection gets queried on the student's behalf, we need to find out if students array already contains the student's ObjectId. Is there a way to specify in the projection of a find query to retrieve student ObjectId from students array only if it is there?
I tried to see if I could $elemMatch operator but it is geared towards an array of sub-documents. I understand that I could use aggregation framework but it seems that it would be on overkill in this case. Aggregation framework would probably not be as fast as a single find query. Is there a way to query course collection to so that the returned document could be in a form similar to this?
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc4"),
"name" : "CS 101",
"students" : [
ObjectId("51780f796ec4051a536015d0"),
]
}
[edit based on this now being possible in recent versions]
[Updated Answer] You can query the following way to get back the name of class and the student id only if they are already enrolled.
db.student.find({},
{_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}})
and you will get back what you expected:
{ "name" : "CS 101", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
{ "name" : "Literature" }
{ "name" : "Physics", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
[Original Answer] It's not possible to do what you want to do currently. This is unfortunate because you would be able to do this if the student was stored in the array as an object. In fact, I'm a little surprised you are using just ObjectId() as that will always require you to look up the students if you want to display a list of students enrolled in a particular course (look up list of Id's first then look up names in the students collection - two queries instead of one!)
If you were storing (as an example) an Id and name in the course array like this:
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
"name" : "Physics",
"students" : [
{id: ObjectId("51780f796ec4051a536015cf"), name: "John"},
{id: ObjectId("51780f796ec4051a536015d0"), name: "Sam"}
]
}
Your query then would simply be:
db.course.find( { },
{ students :
{ $elemMatch :
{ id : ObjectId("51780f796ec4051a536015d0"),
name : "Sam"
}
}
}
);
If that student was only enrolled in CS 101 you'd get back:
{ "name" : "Literature" }
{ "name" : "Physics" }
{
"name" : "CS 101",
"students" : [
{
"id" : ObjectId("51780f796ec4051a536015cf"),
"name" : "John"
}
]
}
It seems like the $in operator would serve your purposes just fine.
You could do something like this (pseudo-query):
if (db.courses.find({"students" : {"$in" : [studentId]}, "course" : courseId }).count() > 0) {
// student is enrolled in class
}
Alternatively, you could remove the "course" : courseId clause and get back a set of all classes the student is enrolled in.
I am trying to explain by putting problem statement and solution to it. I hope it will help
Problem Statement:
Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-
Solution:
Below are the conditions that need to be taken care of
Product price should be less than 15
Product name should be either ABC Product or PQR Product
Product should be in published state.
Below is the statement that applies above criterion to create query and fetch data.
$elements = $collection->find(
Array(
[price] => Array( [$lt] => 15 ),
[$or] => Array(
[0]=>Array(
[product_name]=>Array(
[$in]=>Array(
[0] => ABC Product,
[1]=> PQR Product
)
)
)
),
[state]=>Published
)
);
Related
So I wanna find multiple items so I don't have to loop sense I was told not to do that.
{ "_id" : ObjectId("59d2b1cf8cec1709f85eb7a9"), "title" : "Arrow", "common_movies" : [ ], "__v" : 0 }
{ "_id" : ObjectId("59d2b1cf8cec1709f85eb7aa"), "title" : "Gotham", "common_movies" : [ ], "__v" : 0 }
my database's movie collection looks like this.
and I want an array with 2 items in it, the Arrow and Gotham objects, This is what I tried
Movie.find({title: "Arrow"}, {title: "Gotham"}, function(err, foundMovie){
console.log(foundMovie)
});
If you want to select movies where name is Arrow or Gotham, then you should use or operator in your criteria object: var criteria = { $or: [ {title: 'Arrow'}, {title: 'Gotham'} ]}. See mongodb documentation about OR logical operator.
Then use criteria object in your find method:
Movie.find(criteria, function(err, foundMovie){
console.log(foundMovie)
});
I'm having some trouble determining how to find a document within a collection, and a value within an object in a subarray of that document — and then update a value within an object in that array.
I need to do the following:
find by _id
find object in ratings array that matches the user + post keys
update the report value within that object
For example, the documents in my collection are set up like below.
{
"_id" : "mz32AcxhgBLoviRWs",
"ratings" : [
{
"user" : "mz32AcxhgBLoviRWs",
"post" : "SMbR6s6SaSfsFn5Bv",
"postTitle" : "fdsfasdf",
"date" : "2017-09-27",
"rating" : "4",
"review" : "sdfa",
"report" : "a report"
},
{
"user" : "mz32AcxhgBLoviRWs",
"post" : "iZbjMCFR3cDNMo57W",
"postTitle" : "today",
"date" : "2017-09-27",
"rating" : "4",
"review" : "sdfa",
"report" : "some report"
}
]
}
It seems that you want just one update, not three separated queries.
Collection.update({
_id: <id>,
ratings: {
$elemMatch: {
user: <user>,
post: <post>
}
}
}, {
$set: {
'ratings.$.report': <report>
}
});
Documentation: $elemMatch, <array>.$.
When I try to find specific object in array using find({query}) I always get all elements from array.
Activities array stores activities (it would be a thousands of them) as you can see in the following snippet:
This is my collection:
{
"_id" : ObjectId("58407140755324d04db2ce95"),
"owner" : 103429326776572,
"activities" : [
{
"name" : "test1",
"startTime" : ISODate("2016-08-11T17:41:54Z"),
"type" : "te1",
"lat" : 1,
"lon" : 1,
"creator" : 126212904493088,
"coverPhoto" : {
"name" : "test1",
"path" : "c:\\Users\\Francis\\Desktop\\dusk\\public\\coverPhotos\\SJ9tpP6Mx.jpg"
},
"identifier" : "H1g9F6vpGl",
"users" : [
1,
2,
3
],
"hashTags" : [
"some",
"hashtags"
]
},
{
"name" : "test2",
"startTime" : ISODate("2016-08-11T17:41:53Z"),
"type" : "te2",
"lat" : 1,
"lon" : 1,
"creator" : 103312904493090,
"coverPhoto" : {
"name" : "test2",
"path" : "c:\\Users\\Francis\\Desktop\\dusk\\public\\coverPhotos\\Hy8qpvafe.jpg"
},
"identifier" : "rJlU5TvpMx",
"users" : [
1,
2,
3
],
"hashTags" : [
"some",
"hashtags"
]
}
]
}
I need to get for example an activity that has specific identifier.
I tried to use queries like:
1) db.myCollection.find({'activities.identifier' : "rJlU5TvpMx"})
2) db.myCollection.find({'activities' : { $elemMatch : { "identifier" : "rJlU5TvpMx", "creator" : 103312904493090 } })
And all combinations with '' or "" signs
I found above queries at mongodb docs in equal documents schema as mine is.
Can you tell me what am I doing wrong ?
You can try either use single match or multiple match based on your need. This makes use of $elemMatch(projection)
db.myCollection.find({"_id" : ObjectId("58407140755324d04db2ce95")},
{activities: {$elemMatch: { identifier: "rJlU5TvpMx"}}})
db.myCollection.find( {"_id" : ObjectId("58407140755324d04db2ce95")},
{activities: {$elemMatch: {creator : 103312904493090, identifier: "rJlU5TvpMx" }}})
You are looking for the projection object which gets passed as an argument in your query. It allows the return of specific fields from your search rather than the entire document. http://mongoosejs.com/docs/api.html#model_Model.find
I would also suggest looking at the response to this question here: Mongoose Query: Find an element inside an array which makes use of the unwind operator to enter the array as it seems to be relevant to your needs.
In the collection you are searching in, you have just one Document(Object). If you apply method find() to your collection and the query inside matches the value in activities.identifier it will return the only Document(object).
To have a better understanding of what I am talking about check example on mongoose API doc
And query result here.
Try check this out https://docs.mongodb.com/v3.0/reference/operator/projection/elemMatch/#proj._S_elemMatch instead
I have a collection like User having list user and that user have list of user. Like hierarchy.
{
"_id" : ObjectId("55530326bc687d21783fd1ff"),
"Name" : "User 1",
"Role" : "Manager",
number:NumberLong(0),
"1" :
[
{
"_id" : ObjectId("55530326bc687d21783fd1fd"),
"Name" : "User 2",
"Role" : "Ass Manager",
number:NumberLong(0),
"1" :
[
.......
]
}
{
"_id" : ObjectId("55530326bc687d21783fd1fq"),
"Name" : "User 2",
"Role" : "Ass Manager",
number:NumberLong(1),
"1" :
[
.........
]
},
{
"_id" : ObjectId("55530326bc687d21783fd1fg"),
"Name" : "User 3",
"Role" : "Ass Manager",
number:NumberLong(2),
"1" :
[
........
]
}
],
"2" :
[
{
"_id" : ObjectId("55530326bc687d21783fd1fw"),
"Name" : "User 4",
"Role" : "Specialist",
number:NumberLong(0),
"1" :
[
.......
]
}
{
"_id" : ObjectId("55530326bc687d21783fd1fe"),
"Name" : "User 5",
"Role" : "Specialist",
number:NumberLong(1),
"1" :
[
.........
]
},
{
"_id" : ObjectId("55530326bc687d21783fd1fr"),
"Name" : "User 6",
"Role" : "Specialist",
number:NumberLong(2),
"1" :
[
........
]
}
]
}
The above is just one collection for sample, like this i have nearly 10000 document. I need to find the collection which have 'number' as 0. Even if any one embedded document have 'number' as 0 I want that document.
Note : I can't tell how many child will come for a user.
All right, I will assume that each of your User documents can have two arrays of children users (namely "1" and "2"), and that you have a maximum nesting level, say 3 (This means that a nested user cannot have more than 2 anchestors). By the way, the maximum nesting level allowed by mongodb is 100.
Probably this is not want you wanted: in this case you have issues with your schema design, because
An arbitrarily nested schema is not good
If keys are intended as indexes, you should consider using an array instead of an object (click here for a similar case).
Now, let's pretend that my assumptions were ok for you. Try (I'm calling your collection users since we don't usually capitalize collection names):
db.users.find({$or:["1.number" : 0, "2.number" : 0, "1.1.number":0, "1.2.number":0, ..., "2.2.1.number":0, "2.2.2.number":0]})
I have skipped some combinations that you need to add. Notice that you don't need to worry about the position in arrays, and that with only 3 levels of nesting there are already quite many clauses for the $or operator, and that will possibly convince you that it's better to follow the linked best practices.
NOTE for future readers: the OP has clarified in a comment that he doesn't actually need an update, but a find query.
In my database, I currently have two kinds of objects, users and jobs. I am already storing userIDs in jobs. Do I also need to store jobIDs in each user?
A typical user:
"-JqzUjcOfddBNd_HtjKb" : {
"contact" : {
"-JqzWcIyD77ZwatEKALp" : {
"email" : "someguy#yahoo.com"
},
"-JqzWrtyni3ZGOKooNF7" : {
"email" : "someguy#outlook.com"
}
},
"country" : "234",
"cv" : "https://linktourl.com",
"dateAdded" : 1433436879708,
"ethnicity" : "0",
"firstName" : "John",
"lastName" : "Smith",
"notes" : {
"-JqzhvtNcueUsPr8xwh8" : {
"date" : 1433440599702,
"user" : "iwrotethisnote#example.com",
"value" : "interested in job; need to interview"
}
},
"roles" : [ true ]
},
And a typical job:
"-Jqz5mOr-DmLcxmTVRPi" : {
"age" : [ "2" ],
"city" : "0",
"clientID" : "-Jqz7goZC76vl94VT0dq",
"dateModified" : 1433431226687,
"longDesc" : "Teacher should have experience",
"notes" : {
"-Jqz6SO74OJOESwOVfkG" : {
"date" : 1433430513294,
"notevalue" : "bill spoke with her",
"userid" : "name#gmail.com"
}
},
"schedule" : "Evening or weekend",
"status" : "needDetail",
"subjects" : {
"15" : true,
"42" : true
},
"title" : "She wants a native speaker"
},
As you can see, jobs have a field for clientID, which is a foreign key (so to speak) of a user's id. When I access a user's information, I want to know those jobs that they are associated with (i.e. for which they have supplied their client ID). How to do this in Firebase?
Should I:
Update both objects, and keep an array of jobIDs in the client object?
Query all jobs, then pass in those that have the user's ID as the client ID. Something like:
// user controller
var jobs = [];
jobsRef.$on('value', function(snapshot) {
snapshot.val().forEach(function(job) {
if (job.clientID = $scope.userID) {
jobs.push(job);
}
}
}
Option 1 makes the data redundant (which I guess is ok, because of the emphasis on denormalization), but it also makes it more likely to become out of sync, for example if one of the two updates I would be making fails.
Option 2 seems like it would run a lot slower.
You can use equalTo() of firebase query
var jobsRef = new Firebase();
jobsRef.orderByChild("clientID").equalTo($scope.userID)
.on("value", function(snapshot) {
console.log(snapshot.key());
});
For more info, please check out Query.equalTo()