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)
});
Related
I am new to queries in mongodb. I have a document like this -
{
"_id" : ObjectId("5eb0f70f88cd051e7839325c"),
"id" : "1",
"arrayInfo" : [ {"color":"red"}, {"color":"black"}, {"color":"cyan"} ]
}
There are many documents in this format with changing ids and colors inside arrayInfo. I want to do something like -
Find record with id "1" -> Display object inside array info with {"color" : "cyan"}
I believe I have to chain queries after finding like this -
db.collection('Records').findOne({id:"1"}).**something**
Any help will be appreciated thanks.
if(id===1){
res.arrayInfo.map(item => console.log(item.color))
}
db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )
enter link description here
If no operator is specified, MongoDB by default performs array element matching when the document stores an array. Thus you can simply do:
MongoDB Enterprise ruby-driver-rs:PRIMARY> db.foo.findOne({id:'1',arrayInfo:{color:'cyan'}})
{
"_id" : ObjectId("5eb0f70f88cd051e7839325c"),
"id" : "1",
"arrayInfo" : [
{
"color" : "red"
},
{
"color" : "black"
},
{
"color" : "cyan"
}
]
}
To match one field in the array instead of the complete array element, use $elemMatch.
I have a MongoDB collection with the following structure:
/* 1 */
{
"_id" : ObjectId("5cdb24b41a40ae58e6d690fd"),
"versions" : [
ObjectId("5cdb24b41a40ae58e6d690fe")
],
"releases" : [],
"monetization" : [],
"owner" : "testuser",
"name" : "test-repo-2",
"repoAddress" : "/testuser/test-repo-2",
"repoKey" : null,
"__v" : 0
}
/* 2 */
{
"_id" : ObjectId("5cdb23cb1a40ae58e6d690fa"),
"versions" : [
ObjectId("5cdb23cb1a40ae58e6d690fb"),
ObjectId("5cdda9c54e6d0b795a007960")
],
"releases" : [
ObjectId("5cdda9c54e6d0b795a00795c")
],
"monetization" : [],
"owner" : "testuser",
"name" : "test-repo-1",
"repoAddress" : "/testuser/test-repo-1",
"repoKey" : null,
"__v" : 2,
"createdAt" : ISODate("2019-05-16T18:19:49.159Z"),
"updatedAt" : ISODate("2019-05-16T18:19:49.252Z")
}
I need to loop though all the documents in the collection as well as they array of versions to look for a specific to match it to the project. I need to do this with NodeJS, but for now I'm trying it from mongoshell. I'm trying to use forEach() and $in operator to do this.
db.projects.find().forEach(
function () {
{
versions: {
$in: ['5cdb24b41a40ae58e6d690fe']
}
}
}
);
But each time I get the following response: Script executed successfully, but there are no results to show. Am I doing this correctly?
There are various solutions you could try, for example:
1) You could add a filter to your find-query:
db.getCollection('debug').find({"versions":{"$in":[ObjectId("5cdb24b41a40ae58e6d690fe")]}})
This would directly return the object you're looking for.
2) If you don't want to pass a filter and really query all documents and filter them yourself, you could try the following:
db.getCollection('debug').find({}).forEach(doc => {
doc.versions.forEach(v => {
if(v.toString() === "ObjectId(\"5cdb24b41a40ae58e6d690fe\")") {
print("match");
}
});
});
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
)
);
I am querying MongoDB using Mongoose and getting the record along with populated records, However i would like to sort the populated records i am receiving.
const record = Model.findOne({ '_id': '10b9ad30be4c3c0e98cf199q' });
{
"_id" : 10b9ad30be4c3c0e98cf199q,
"name" : "Hello World",
"_order" : [ "28b802cd0588741258d01120", 28b802cd0588741258d01130"", "28b802cd0588741258d01140" ],
}
And, After populating It looks like
const record = Model.findOne({ '_id': '10b9ad30be4c3c0e98cf199q' }).populate('items');
{
"_id" : 10b9ad30be4c3c0e98cf199q,
"name" : "Hello World",
"_order" : [ "28b802cd0588741258d01120", 28b802cd0588741258d01130"", "28b802cd0588741258d01140" ],
"items" : [
{ "_id" : 28b802cd0588741258d01140, name: "Games" },
{ "_id" : 28b802cd0588741258d01120, name: "Movies" }
{ "_id" : 28b802cd0588741258d01130, name: "Science?" }
]
}
How can i effectively sort the populated records items based on its _id in the _order field?
Is it even possible or do i have to do it client side/in server after getting the record.
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