I have a db that looks like this :
{
"_id" : ObjectId("50525e55467f67da3f8baf06"),
"client" : "client1"
}
{
"_id" : ObjectId("505262f0deed32a758410b1c"),
"client" : "client2"
}
{
"_id" : ObjectId("5052fe0a37083fd981616589"),
"client" : "client3",
"products" : [
{"name" : "product1"},
{"name" : "product2"}
]
}
How can i retrieve the product list of client3 without retrieving the client3 record ?
The output should look like this :
[
{"name" : "product1"},
{"name" : "product2"}
]
I don't think you can completely exclude the client3 record as the products are part of this record, but you can select just the products field like this:
db.<dbname>.find({ 'client' : 'client3' }, { 'products' : 1, '_id' : 0 })
Also - if you want to get just the matching subrecord - see here
http://docs.mongodb.org/manual/reference/operator/projection/positional/
you use the $ operator in the project portion of find to specify the n'th subrecord where that is the first to match your query.
Related
I have two different collection in two different MongoDB databases.
Collection users in db1:
{
"_id" : "xyz",
"name" : "John",
"project_id" : "abc"
}
Collection project in db2:
{
"_id" : "abc",
"regionCode" : "1AB"
}
Now I want to get list of all users who belong to region 1AB. How do I achieve that.
I read about DBRefs. So I changed structure of collections users but still i can not query directly to reference collection attribute directly
collection users new structure :
{
"_id" : "xyz",
"name" : "John",
"project_id" : "abc",
"projectData" : {
"$ref" : "project",
"$id" : "abc",
"$db" : "db2"
}
}
Now how do I get list of all users that belong to project regioncode 1AB.
I am using nodejs native client
I have to delete the second comment using index value.. Following is my document structure
{
"_id" : ObjectId("000000000fea5f24282e715b"),
"file_name" : "resume_of_ganga_.docx",
"created_date" : ISODate("2017-11-28T10:29:10.373Z"),
"updated_date" : ISODate("2017-11-28T12:39:32.148Z"),
"comments" : [
{
"created_date" : ISODate("2017-11-28T13:23:51.472Z"),
"status" : "N",
"comment_text" : "Yes...",
"username" : "name"
},
{
"created_date" : ISODate("2017-11-28T13:24:15.938Z"),
"status" : "N",
"comment_text" : "asdsd",
"username" : "name"
}
]
}
I have using this following mongoose query..But my comments are not get deleting
mongo.filemanager.findOneAndUpdate({ "_id": req.body.id},{$pull : {"'comments.' +req.body.c_index" : 1 }},function(err,response){
console.log("Deleted")
});
For example am getting index value as 2.. It should delete the second comment...
Thanks in Advance
I tried looking up to see if MongoDB has any such functionality but seems like they don't from what I found.
A workaround could be something like this. Not sure if this can be considered an atomic operation.
const removeCommentAtIndex = (index) => {
mongo.filemanager.findById(req.body.id, (err, file) => {
file.comments.splice(index, 1);
file.save();
})
}
I executed the accepted answer for In mongoDb, how do you remove an array element by its index in my test database and IT WORKS
mongo.filemanager.findOneAndUpdate({}, {"$unset" : {"comments.1" : 1 }})
mongo.filemanager.findOneAndUpdate({}, {"$pull" : {"comments" : null}})
Note that your req.body.c_index needs to be 1 to remove 2nd comment.
Hyy , I have a collection where comments related to the blog are stored in multiple document as shown below.
[
{
"_id" : ObjectId("565f0f5d77f0c7bd11bbadd8"),
"blog_id" : ObjectId("56587befdb7224110f007233"),
"comments" : [
{
"user_id" : ObjectId("562fa014888806820e21e0df"),
"user_full_name" : "Niroj Paudel",
"comment" : "pradip is bhole baba",
"_id" : ObjectId("565f0f5d77f0c7bd11bbadd9"),
"dt" : ISODate("2015-12-02T15:33:49.578Z")
},
{
"user_id" : ObjectId("562fa014888806820e21e0df"),
"user_full_name" : "Niroj Paudel",
"comment" : "honkog pokhara... he he ha ha",
"_id" : ObjectId("565f1034fd07cbfc1129db0b"),
"dt" : ISODate("2015-12-02T15:37:24.581Z")
}
],
"record_count" : 2,
"__v" : 0
}
{
"_id" : ObjectId("565efa37635f09900d21a339"),
"blog_id" : ObjectId("56587befdb7224110f007233"),
"comments" : [
{
"user_id" : ObjectId("562fa014888806820e21e0df"),
"user_full_name" : "Niroj Paudel",
"comment" : "wat a nice car wow",
"_id" : ObjectId("565efa37635f09900d21a33a"),
"dt" : ISODate("2015-12-02T14:03:35.289Z")
},
{
"user_id" : ObjectId("562fa014888806820e21e0df"),
"user_full_name" : "Niroj Paudel",
"comment" : "love is life budikhola ma dives",
"_id" : ObjectId("565efa76635f09900d21a33b"),
"dt" : ISODate("2015-12-02T14:04:38.661Z")
},
{
"user_id" : ObjectId("562fa014888806820e21e0df"),
"user_full_name" : "Niroj Paudel",
"comment" : "bholi ajaya ko bihe",
"_id" : ObjectId("565efaa0635f09900d21a33c"),
"dt" : ISODate("2015-12-02T14:05:20.847Z")
},
{
"user_id" : ObjectId("562fa014888806820e21e0df"),
"user_full_name" : "Niroj Paudel",
"comment" : "manish is nice",
"_id" : ObjectId("565efb17635f09900d21a33d"),
"dt" : ISODate("2015-12-02T14:07:19.704Z")
},
{
"user_id" : ObjectId("562fa014888806820e21e0df"),
"user_full_name" : "Niroj Paudel",
"comment" : "niroj is cool",
"_id" : ObjectId("565efd53c22dddc80e8f461c"),
"dt" : ISODate("2015-12-02T14:16:51.730Z")
},
{
"user_id" : ObjectId("562fa014888806820e21e0df"),
"user_full_name" : "Niroj Paudel",
"comment" : "ramesh is cool",
"_id" : ObjectId("565f0d376d82e24c11f6c0d1"),
"dt" : ISODate("2015-12-02T15:24:39.010Z")
}
],
"record_count" : 6,
"__v" : 0
}
]
Suppose user wants to update his comment; for this I would have the comments _id now my problem is that how can I detect in which document the comment exist based of the comment _id value of comments array field.
suppose I have a comment "_id" : "565f0f5d77f0c7bd11bbadd9" (first element of first document)
then the result should give the parent document _id:"565f0f5d77f0c7bd11bbadd8" (first document id)
How can I do this..
Thank you in advance
if possible, then please update your schema.
Suppose you have collection of Blog. Then your code will be :
Blog.find({'comments._id' : '565f0f5d77f0c7bd11bbadd9'}).exec(function(err,blog){
if(!err && blog){
console.log("Blog id :"+blog._id);
}
else{
console.log("Dont get your blog");
}
});
if your comments are directly stored on the blog document you could go with an aggregate method to collect the comment across all documents. note that this seems to work when you don't have any object references to be populated.
asuming all documents are based on a blog Schema and that you wish to recieve the id of the comment:
Blog.aggregate(
[{'$match':{'comments':{'$elemMatch:{'_id':'565f0f5d77f0c7bd11bbadd9'}}}},
{'$project':{comments:'$_id', user_id:1}},
{'$unwind':'$comments'}
{'$group':{_id:'$comments'}}
]).exec(function(err, results){
if(results){
console.log(results);
}
});
I hope this is somewhat what you're looking for, you might find the following read usefull
elementMatch and aggregation from the mongoDB docs.
cheers!
The site recommended this old question to me as being Related to another I was looking at. Looks like a sufficient answer wasn't ever given, so I'll provide it for any future readers.
The requested behavior here is very straightforward to achieve with a basic find() query:
db.collection.find(
{ "comments._id": ObjectId("565f0f5d77f0c7bd11bbadd9") },
{ _id: 1 }
)
Here we are filtering the documents based on the values of the _id fields embedded in the comments array. Then for the matching document(s) we are applying a projection to just retrieve the _id field of the "parent document" (e.g. the document that was matched). If the _ids for the comments are unique then there will only ever be a maximum of a single matching document. Sample playground demonstration is here.
A more complicated aggregation would have only been necessary here if the intent was to always provide the _id value of the first document associated with a given blog_id but that does not appear to be the case here.
In Node with Mongoose I want to find an object in the collection Content. It has a list of sub-documents called users which has the properties stream, user and added. I do this to get all documents with a certain user's _id property in there users.user field.
Content.find( { 'users.user': user._id } ).sort( { 'users.added': -1 } )
This seems to work (although I'm unsure if .sort is really working here. However, I want to match two fields, like this:
Content.find( { 'users.user': user._id, 'users.stream': stream } } ).sort( { 'users.added': -1 } )
That does not seem to work. What is the right way to do this?
Here is a sample document
{
"_id" : ObjectId("551c6b37859e51fb9e9fde83"),
"url" : "https://www.youtube.com/watch?v=f9v_XN7Wxh8",
"title" : "Playing Games in 360°",
"date" : "2015-03-10T00:19:53.000Z",
"author" : "Econael",
"description" : "Blinky is a proof of concept of enhanced peripheral vision in video games, showcasing different kinds of lens projections in Quake (a mod of Fisheye Quake, using the TyrQuake engine).\n\nDemo and additional info here:\nhttps://github.com/shaunlebron/blinky\n\nThanks to #shaunlebron for making this very interesting proof of concept!\n\nSubscribe: http://www.youtube.com/subscription_center?add_user=econaelgaming\nTwitter: https://twitter.com/EconaelGaming",
"duration" : 442,
"likes" : 516,
"dislikes" : 13,
"views" : 65568,
"users" : [
{
"user" : "54f6688c55407c0300b883f2",
"added" : 1427925815190,
"_id" : ObjectId("551c6b37859e51fb9e9fde84"),
"tags" : []
}
],
"images" : [
{
"hash" : "1ab544648d7dff6e15826cda7a170ddb",
"thumb" : "...",
"orig" : "..."
}
],
"tags" : [],
"__v" : 0
}
Use $elemMatch operator to specify multiple criteria on an array of embedded documents:
Content.find({"users": {$elemMatch: {"user": user.id, "stream": stream}}});
I have the following user schema
{
"__v" : 26,
"_id" : ObjectId("52b47058fe5e3493a2cf8365"),
"live_sockets" : [
"CEGok0rSz2UtBIHX9DlV",
"s6M45OA0MDBs4aGL9DlW",
"2XiszSuyiPAGr-Ga9ZCN",
"lIFNEeUgXRB6tgvP9ZCO",
"JPtzQOD_52maf6VS9gtb",
"kDL06aXiI8WWlig19gtc",
"75Bt5p6WqgmRcyer9xSm",
"Ge_sKLen32Q91wLW9xSn",
"EpHt3qju34GTZevU_Bsd",
"n0hq0EQAjJOptxdy_qEB",
],
"name" : {
"first" : "Test",
"last" : "User"
},
"notifications_count" : 0,
"role" : 1
}
How can i query a user based on a particular live socket as socket_ids are unique.
If i have a variable called current_socket_id how can i find a user which the socket belongs to..?
db.collection.find({"live_sockets" : {$in : [socketId]}},{"name" : 1,"_id":0})
Will give the name for the socket id