Mongodb find query for array - node.js

i'm trying - find query for array in mongodb,
db.users.find({posts:{$all:[_id : ObjectId("5cc83a158ceb346aa58b1161")]}})
db.users.find( { "posts.post" : {$all : []}})
//My MongoDB collections
> db.users.find().pretty()
{
"_id" : ObjectId("5cc83a158ceb346aa58b1161"),
"friends" : [ ],
"name" : "krishna soni",
"email" : "krishnasoni#gmail.com",
"password" : "krishna",
"posts" : [
{
"_id" : ObjectId("5cc8478118195b71e2ccd517"),
"post" : "hey users",
"createdTime" : ISODate("2019-04-30T13:02:57.621Z")
},
{
"_id" : ObjectId("5cc853ec0a5fde0e431898f3"),
"post" : "hey friends it's my final post",
"createdTime" : ISODate("2019-04-30T13:55:56.119Z")
}
],
"__v" : 0
}
//expected results is following
//display given objectId's posts array
"posts" : [
{
"_id" : ObjectId("5cc8478118195b71e2ccd517"),
"post" : "hey users",
"createdTime" : ISODate("2019-04-30T13:02:57.621Z")
},
{
"_id" : ObjectId("5cc853ec0a5fde0e431898f3"),
"post" : "hey friends it's my final post",
"createdTime" : ISODate("2019-04-30T13:55:56.119Z")
}
],

You just need to pass {posts:1}
Try this:
db.users.find({"_id" : ObjectId("5cc83a158ceb346aa58b1161")},{posts:1});

Related

How do I access an element in a nested schema?

{
"_id" : ObjectId("5b8d1ecbb745685c31ad8603"),
"name" : "abc",
"email" : "abc#gmail.com",
"projectDetails" : [
{
"technologies" : [
"abc",
"abc"
],
"_id" : ObjectId("5b8d1ecbb745685c31ad8604"),
"projectName" : "abc",
"projectDescription" : "abc",
"manager" : "abc",
"mentor" : "abc"
}
],
"__v" : 0
}
Here, projectDetails is an array of objects. I want to update the element "projectName" in projectDetails. How do I write a PUT request for the same in Postman?
Try below query
db.users.update({ "email" : "abc#gmail.com","projectDetails._id":ObjectId("5b8d1ecbb745685c31ad8604")},{ $set: { "projectDetails.$.projectName" : "test" } })
Your url should be like this
http://localhost:3000/project/5b8d1ecbb745685c31ad8604
Your put request as mentioned below
router.route("/updateProject",function(req,res){
var id = req.query.project_id; // Check syntax for framework you are using
});

Mongo pull object from array inside array

i have inside my mongoDB collection this document
{
"_id" : ObjectId("5b633025579fac22e74bf3be"),
"FLAGS" : [
{
"toSent" : [
{
"_id" : ObjectId("5b633025579fac22e74bf3c2"),
"phone" : "+84404040404"
},
{
"_id" : ObjectId("5b633025579fac22e74bf3c1"),
"phone" : "+212652253403"
},
{
"_id" : ObjectId("5b633025579fac22e74bf3c0"),
"phone" : "+212123456788"
}
],
"_id" : ObjectId("5b633025579fac22e74bf3bf"),
"action" : "group_p_a"
},
{
"toSent" : [
{
"_id" : ObjectId("5b633031579fac22e74bf3c9"),
"phone" : "+212651077199"
},
{
"_id" : ObjectId("5b633031579fac22e74bf3c8"),
"phone" : "+84404040404"
},
{
"_id" : ObjectId("5b633031579fac22e74bf3c7"),
"phone" : "+212652253403"
},
{
"_id" : ObjectId("5b633031579fac22e74bf3c6"),
"phone" : "+212123456788"
}
],
"_id" : ObjectId("5b633031579fac22e74bf3c5"),
"action" : "group_p_a"
}
],
"time" : ISODate("2018-08-02T16:24:05.747+0000"),
"action_user_phone" : "+212123456788",
"idGroup" : "e534379a-1580-4568-b5ec-6eaf981538d2",
"nomGroup" : "MOH FOR EVER",
"__v" : NumberInt(0)
}
TODO
I need to remove for example this element { "_id" : ObjectId("5b633025579fac22e74bf3c2"), "phone" : "+84404040404"}
WHAT I DID
GroupEvents.update({}, {$pull:{FLAGS:{$elemMatch:{toSent:{phone: "+84404040404"} }}}},function(err,ret){
if(err)
console.log("error"+err);
if(ret)
console.log(ret);
});
It remove all what's inside toSent event if it doesn't match.
Any help please
You need to use $ positional operator instead of $elemMatch here
GroupEvents.update(
{ "Flags.toSent.phone": "+84404040404" },
{ "$pull": { "FLAGS.$.toSent": { "phone": "+84404040404" }}},
)
If you want remove from every element of FLAGS array this you need to use $[] the all positional operator
GroupEvents.update(
{ "Flags.toSent.phone": "+84404040404" },
{ "$pull": { "FLAGS.$[].toSent": { "phone": "+84404040404" }}},
)

Targeting a query in Mongo to find and email nested in an object

I'm trying to do a query for an endpoint in my Node/Express & Mongo/Mongoose API.
Here is a representation of the document/schema I'm trying to query:
{
"_id" : ObjectId("59474bc3478604a75e1980e2"),
"initial" : "D",
"last_name" : "Spitz",
"first_name" : "Chris",
"owner_id" : "59474b92478604a75e1980e1",
"contacts" : [
{
"last_name" : "Jones",
"first_name" : "Tom",
"_id" : ObjectId("5947fd928389ffb393fbc310"),
"addresses" : [ ],
"phones" : [ ],
"emails" : [
{
"email_type" : "home",
"email_address" : "runner#running.com",
"_id" : ObjectId("5947fd928389ffb393fbc311")
},
{
"email_type" : "home",
"email_address" : "jake#samsonite.com",
"_id" : ObjectId("5947ff9ed8fa7cb4c781acc9")
}
]
},
{
"last_name" : "Smith",
"first_name" : "Linda",
"_id" : ObjectId("5947ff9ed8fa7cb4c781acc8"),
"addresses" : [ ],
"phones" : [ ],
"emails" : [
{
"email_type" : "home",
"email_address" : "chris#chrisnakea.com",
"_id" : ObjectId("5947ff9ed8fa7cb4c781acc9")
}
]
}
]
}
I'm trying to check if an email exists in the "contacts.email" array of the document.
Here is the way I'm checking (based on the whey it the item is nested in the schema above):
Profile.find({'contacts.emails.email_address':req.body.invited_email}, function(err, profile){
if(err)
console.log('Error in looking for profile.');
if(profile.contacts.emails.email_address !== null){
console.log('Found contact: ' + profile.contacts.emails.email_address);
} else {
console.log('Contact does not exist');
}
})
But for some reason I'm getting a "TypeError: Cannot read property 'emails' of undefined" error in the console when testing.
What am I missing here?

Mongoose Query Help: Paginate, Sort, Limit on Nested Array

I am have a chat Mongoose model in the below is the sample data. If this is still not clear please revert back to me with your questions. Any help is greatly appreciated.
{
"_id" : ObjectId("5745910831a1sd58d070a8faa"),
"messages" : [
{
"user" : "user1",
"message" : "How are you user1?",
"readInd" : "N",
"createDate" : ISODate("2016-05-25T11:36:00.468+0000"),
"_id" : ObjectId("5745912c31a1c58d070a904d")
},
{
"user" : "user1",
"message" : "Hello user1",
"readInd" : "N",
"createDate" : ISODate("2016-05-25T11:38:53.893+0000"),
"_id" : ObjectId("5745912531a1c58d070a902e")
}
],
"createDate" : ISODate("2016-05-25T11:35:20.534+0000"),
"users" : [
"57450b4506561ff5052f0a66",
"57450d8108d8d22c06cf138f"
],
"__v" : NumberInt(0)
},
{
"_id" : ObjectId("57458e9331a1c58d070a8e30"),
"messages" : [
{
"user" : "user2",
"message" : "How are you user2",
"readInd" : "N",
"createDate" : ISODate("2016-05-25T11:46:03.240+0000"),
"_id" : ObjectId("574590f331a1c58d070a8ede")
},
{
"user" : "user2",
"message" : "Hello user2",
"readInd" : "N",
"createDate" : ISODate("2016-05-25T11:48:53.925+0000"),
"_id" : ObjectId("574590e931a1c58d070a8eab")
}
],
"createDate" : ISODate("2016-05-25T11:35:20.534+0000"),
"users" : [
"5745149e3aaab38706c00b64",
"57450d8108d8d22c06cf138f"
],
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("5745910831a1c58d070a8faa"),
"messages" : [
{
"user" : "user3",
"message" : "How are you user3?",
"readInd" : "N",
"createDate" : ISODate("2016-05-25T11:56:00.468+0000"),
"_id" : ObjectId("5745912c31a1c58d070a904d")
},
{
"user" : "user3",
"message" : "Hello user3",
"readInd" : "N",
"createDate" : ISODate("2016-05-25T11:58:53.893+0000"),
"_id" : ObjectId("5745912531a1c58d070a902e")
}
],
"createDate" : ISODate("2016-05-25T11:35:20.534+0000"),
"users" : [
"57450b4506561ff5052f0a66",
"57450d8108d8d22c06cf138f"
],
"__v" : NumberInt(0)
},
{
"_id" : ObjectId("5745910831a1c58d070a8faa"),
"messages" : [
{
"user" : "user4",
"message" : "How are you user4?",
"readInd" : "N",
"createDate" : ISODate("2016-05-25T11:66:00.468+0000"),
"_id" : ObjectId("5745912c31a1c58d070a904d")
},
{
"user" : "user4",
"message" : "Hello user4",
"readInd" : "N",
"createDate" : ISODate("2016-05-25T11:68:53.893+0000"),
"_id" : ObjectId("5745912531a1c58d070a902e")
}
],
"createDate" : ISODate("2016-05-25T11:35:20.534+0000"),
"users" : [
"57450b4506561ff5052f0a66",
"57450d8108d8d22c06cf138f"
],
"__v" : NumberInt(0)
}
below is the explanation:
user1 sent 2 messages at 11:36 and 11:38 respectively
user2 sent 2 messages at 11:46 and 11:48 respectively
user3 sent 2 messages at 11:56 and 11:58 respectively
user4 sent 2 messages at 11:66 and 11:68 respectively
My Expected Result is:
Pagination/limit Criteria:
show 2 records per page.
show only the Most recent message based on user.
Sample output:
Page1:
"user" : "57450d8108d8d22c06cf138f",
"message" : "How are you user4?"
"user" : "57450d8108d8d22c06cf138f",
"message" : "How are you user3?"
Page2:
"user" : "57450d8108d8d22c06cf138f",
"message" : "How are you user2"
"user" : "57450d8108d8d22c06cf138f",
"message" : "How are you user1?"
try this way of query , this is help to u
query for page one
db.getCollection('message').aggregate( [ { $match : { user : "57450d8108d8d22c06cf138f" } },
{ $unwind : "$messages" } ,
{ $sort : { 'messages.createDate' : -1} },
{ $limit : 2 },
{ $project : { _id: 0,'message':'$messages.message','user':'$messages.user'} } ])
query for next page
db.getCollection('message').aggregate( [ { $match : { user : "57450d8108d8d22c06cf138f" } },
{ $unwind : "$messages" } ,
{ $sort : { 'messages.createDate' : -1} },
{ $limit : 2 },{ $skip : 2 }
{ $project : { _id: 0,'message':'$messages.message','user':'$messages.user'} } ])

How to find how to find subdocuments within an array where array in each subdocument contains certain keyword?

I am creating twitter clone using mongodb and want to search tweets which have certain hashtag in them. I came up with following document structure for my database -
{
"_id" : ObjectId("56f88c038c297eb4048e5dff"),
"twitterHandle" : "abhayp",
"firstName" : "Abhay",
"lastName" : "Pendawale",
"emailID" : "abhayp#gmail.com",
"password" : "278a2c36eeebde495853b14e6e5525fd12074229",
"phoneNumber" : "12394872398",
"location" : "San Jose",
"birthYear" : 1992,
"birthMonth" : 0,
"birthDay" : 1,
"followers" : [
"abhayp",
"deepakp",
"john",
"madhuras",
"nupurs",
"vgalgali"
],
"following" : [
"abhayp",
"abhinavk",
"ankitac",
"anupd",
"arpits"
],
"tweets" : [
{
"tweet_id" : "3f0fe01f8231356f784d07111efdf9d8ead28133",
"tweet_text" : "This new twitter sounds good!",
"created_on" : ISODate("2016-03-13T01:47:37Z"),
"firstName" : "Abhay",
"lastName" : "Pendawale",
"twitterHandle" : "abhayp",
"tags" : [ ]
},
{
"tweet_id" : "4e57b6d7d6b47d69054f0be55c238e8038751d84",
"tweet_text" : "#CMPE273 Node.js is #awesome",
"created_on" : ISODate("2016-03-07T23:16:39Z"),
"firstName" : "Abhay",
"lastName" : "Pendawale",
"twitterHandle" : "abhayp",
"tags" : [
"awesome",
"CMPE273"
]
},
{
"tweet_id" : "e5facd5f37c44313d5be02ffe0a3ca7190affd6b",
"tweet_text" : "Getting an incredible welcome in #Pune #travel #adventure #film #india ",
"created_on" : ISODate("2016-03-07T23:37:27Z"),
"firstName" : "Abhay",
"lastName" : "Pendawale",
"twitterHandle" : "abhayp",
"tags" : [
"adventure",
"film",
"india",
"Pune",
"travel"
]
},
{
"tweet_id" : "f5a735c1f747732f3e04f6cb2c092ff44750c0fd",
"tweet_text" : "The D Day today!\n#TheDDay",
"created_on" : ISODate("2016-03-18T22:24:57Z"),
"firstName" : "Abhay",
"lastName" : "Pendawale",
"twitterHandle" : "abhayp",
"tags" : [ ]
}
]}
I want to find out the tweets which have "Pune" in the tags array of the tweet. I tried following command
db.users.find({ "tweets.tags" : {$all: ["Pune"] }}, { tweets : 1 }).pretty();
but this command returns me ALL tweets of users who have 'Pune' entry in tags of one of their tweets. How can search only those tweets which have 'Pune' entry in their tags array?
Note: I don't want users who have tweeted #Pune, rather I want all tweets which contain #Pune. The duplicate marked question does not solve this problem.
Running following query -
db.users.aggregate([{
$match: {
'tweets.tags': 'Pune'
}
}, {
$project: {
tweets: {
$filter: {
input: '$tweets',
as: 'tweet',
cond: {
$eq: ['$$tweet.tags', 'Pune']
}
}
}
}
}]);
returns following results -
{ "_id" : ObjectId("56f88c038c297eb4048e5df1"), "tweets" : [ ] }
{ "_id" : ObjectId("56f88c038c297eb4048e5dff"), "tweets" : [ ] }
{ "_id" : ObjectId("56f88c038c297eb4048e5e07"), "tweets" : [ ] }
Which is certainly not what I want! :(
I don't think that's possible, beside using some convoluted aggregation stages.
The projection operator is close but only returns the first match.
My advice would be to put the tweets in a separate collection, that would be much more convenient to browse them, and probably more scalable. You're already duplicating the relevant user infos in them, so you don't have to change their content.

Resources