I have a structure which looks like below:
course: { // course
id,
coursename,
sections: { // has an array of sections
section: {
id,
sectionname
cards: { // each section has an array of cards
card: {
id
cardname
}
}
}
}
}
Now, I am given the card ID. Suppose cardID is 301. I don't have details about the course or the section in which the card is stored. I only have the cardID. I want to update the cardname from "Test 1" to "Test 2".
Please provide some information about how to update the name of card given only the cardId. Also please provide information about how I can access a single card using only cardId.
If i run the following query:
db.course.find( {"sections.cards.id" : ObjectId("5859517447c4286d0f0639ee")},
{"sections.cards.$":1,_id:0})
The whole section object is returned instead of returning a single card. Please provide some infromation about how to access a single card using only cardId.
An example of document that i have:
{
"_id" : ObjectId("58595041cfdc46100f92a985"),
"modelType" : "Course",
"name" : "c1",
"sections" : [
{
"id" : ObjectId("5859504dcfdc46100f92a986"),
"name" : "s1",
"cards" : [
{
"id" : ObjectId("58595057cfdc46100f92a987"),
"name" : "card1",
},
{
"id" : ObjectId("5859506ccfdc46100f92a988"),
"name" : "card2"
}
]
}
]
}
Please provide information about how to update a card using only card Id.
Suppose I want to change the card's name. How do I achieve it?
I hope this answer is enough for your needs:
which result in(I tested it using your sample):
Explanation:
mongojs
ormongoose
and how to do this within their respective manual),unwind
operation according to your requirement. In this case: which card match your IDTo Update properties inside a document:
It's impossible to update an element inside of an array without knowledge of its index, so first, you must find out its index/position inside. The simplest way I could think of is by using
for
(since yours is double tier-ed array, I think mapReduce method will be much more complicated):The best solution
The best solution is: Don't have this kind of document in the first place. schema-free database approach DOESN'T mean that you can put everything inside a document. You had to consider the functionality and accessibility of data inside next time you design the document schema.
You can rationalize the documents according to your needs. In this case, you should split the
course
document, since it clear thatcard
property should be an independent collection fromcourse
. If you worry that you'll need to join both collection, worry not. Since 3.2 mongodb introduced $lookup for this kind of application.Not only it'll make your life easier, it'll make mongo queries run faster too.