nodejs - how to search within last some documents in mongo - node.js

Nodejs
dbo.collection("abc")
.find({"name": "Felicity"})
.sort({_id:-1})
.limit()
.exec(
function(err, results){
// my code
}
);
Data in Collection
cansOne = [
{
"_id": ObjectId("5ace23558980..."),
"name": "Khalichi",
"gender": "F",
"type":"Admin"
},
.
.
.
{
"_id": ObjectId("5ace23558980..."),
"name": "Thore",
"gender": "M",
"type":""
},
{
"_id": ObjectId("5ace23558980..."),
"name": "John Snow",
"gender": "M",
"type":"Admin"
},
{
"_id": ObjectId("5ace23558980..."),
"name": "Felicity",
"gender": "F",
"type":"User"
}
]
cansTwo = [
{
"_id": ObjectId("5ace23558980..."),
"name": "Khalichi",
"gender": "F",
"type":"Admin"
},
.
.
.
{
"_id": ObjectId("5ace23558980..."),
"name": "Thore",
"gender": "M",
"type":""
},
{
"_id": ObjectId("5ace23558980..."),
"name": "John Snow",
"gender": "M",
"type":"Admin"
},
{
"_id": ObjectId("5ace23558980..."),
"name": "Felicity",
"gender": "F",
"type":"User"
}
{
"_id": ObjectId("5ace23558980..."),
"name": "Batman",
"gender": "M",a
"type":""
}
]
I have this type of data in collection. there are two type of cases:
1) "type":"" at the end of collection, means it is last document of collection.
2) After "type":"" document, there are some documents in collection.
I want to search one document, but if it is coming after last index of "type":"" document then it will return that doc otherwise it will return null. in short I want to search this record in those amount of data which are comes after last "type":""
Can anyone help.
Thanks in advance.
For example I want to search "name": "Felicity".
Expected output
caseOne = [
{
"_id": ObjectId("5ace23558980..."),
"name": "Felicity",
"gender": "F",
"type":"User"
}
]
caseTwo = []

Are you trying to do this with Mongo query alone, or with your application code? Mongo query alone cannot do this AFAIK, you cannot find a document depends on its relative position to other documents. You need to use application code along with Mongo query, something like:
dbo.collection("abc").find({
$or: [{
name: "Felicity"
}, {
type: ""
}]
})
.sort({
_id: -1
})
.limit()
.exec(
function(err, results) {
// results here contains documents having name: Falicity or type: ""
// do your check here
}
);

Related

How to find data based on sub-field name in MongoDB using Mongoose?

There is a sub-field called 'name' in MongoDB Collection (User):
[
{
"teacher": {
"name": "Alex",
"email": "alex#domain.com"
},
"waiter": {
"name": "Feliks",
"email": "feliks#domain.com"
},
"pilot": [
{
"name": "Sam",
"email": "sam#domain.com"
},
{
"name": "alice",
"email": "alice#domain.com"
}
],
},
{
"teacher": {
"name": "max",
"email": "max#domain.com"
},
"waiter": {
"name": "Sam",
"email": "sam#domain.com"
},
"pilot": [
{
"name": "richard",
"email": "richard#domain.com"
},
{
"name": "alice",
"email": "alice#domain.com"
}
],
}
]
How can I find data based on the field 'name'. For example, when I'm looking for 'Sam', it should return me the all documents since 'Sam' is in "waiter" and "pilot" in first and second documents respectively.
I cannot do something like:
User.find({"teacher.name": "Sam", "waiter.name": "Sam", "pilot.name": "Sam" })
This will return me nothing as it is an AND logic. What I need is an OR logic.
You can use the $or operator.
So the query should look like this:
User.find({ $or: [
{ "teacher.name": "Sam" },
{ "waiter.name": "Sam" },
{ "pilot.name": "Sam" }
]
});
Read here for me details.

Mongoose Sort by elements in array

i have my docs like this :
[
{
"_id": "1",
"name": "Valerio",
"gender": "M",
"favorites": []
},
{
"_id": "2",
"name": "Samad",
"gender": "M",
"favorites": ["1", "3", "4"]
},
{
"_id": "3",
"name": "Ayub",
"gender": "F",
"favorites": ["1", "4"]
},
{
"_id": "4",
"name": "Apour",
"gender": "M",
"favorites": ["2"]
}
]
and I want to sort them based on _id : "1" exists in the favorites array like this :
[
{
"_id": "2",
"name": "Samad",
"gender": "M",
"favorites": ["1", "3", "4"]
},
{
"_id": "3",
"name": "Ayub",
"gender": "F",
"favorites": ["1", "4"]
},
{
"_id": "4",
"name": "Apour",
"gender": "M",
"favorites": ["2"]
},
{
"_id": "1",
"name": "Valerio",
"gender": "M",
"favorites": []
}
]
here is what I'm using but this is not sorting it's just filtering :
User.find({
$and: [
{ favorites: { $all: [mongoose.Types.ObjectId("1")] } },
{ gender: { $in:['M'] } },
],
})
i would really appreciate any help, thank you in advance.
You can add a temporary key that holds 1 if the key exists
and 0 if the key doesn't exist, sort in descending order based on this temporary key.
db.collection.aggregate([
{
"$addFields": {
"searchElemExists": {
"$cond": {
"if": {
"$in": [
"1", // <-- Value you want to be sorted based on existance
"$favorites"
]
},
"then": 1,
"else": 0
}
}
},
},
{
"$sort": {
"searchElemExists": -1
}
},
{
"$project": {
"searchElemExists": 0,
},
},
])
Playground Execution of Sample Data

How to query nested object in mongodb

I'm new to mongodb and I've been trying to query this doc for awhile now.
Im trying to query all the rooms that have a room name of 100.
json
{
"count": 3,
"reviews": [
{
"_id": "5f9d42a0a8e71e004643f584",
"user": {
"_id": "5f7308cde0a4a7a66bc3d184",
"name": "Guest"
},
"room": {
"_id": "5f98f9321fd5bb0045b3d886",
"name": "100",
},
"rating": 4,
},
{
"_id": "5f9d431ea8e71e004643f585",
"user": {
"_id": "5f7308cde0a4a7a66bc3d184",
"name": "Guest",
},
"room": {
"_id": "5f98f9321fd5bb0045b3d886",
"name": "100",
},
"rating": 5,
},
{
"_id": "5f9e74fea6c06a0046d3cae2",
"user": {
"_id": "5f7308cde0a4a7a66bc3d184",
"name": "Guest",
},
"room": {
"_id": "5f98fa8b1fd5bb0045b3d88a",
"name": "300",
},
"rating": 5,
}
]}
what I've tried
1. find({},{"reviews.room.name": {$eq: "100"}}) // getting a projection error
2. find({"reviews.room.name": "100"}) // getting null
Any help to the right direction would be greatly appreciated.
Check out the docs about how to use find:
https://docs.mongodb.com/manual/reference/method/db.collection.find/
and try this
db.reviews.find({
"room.name": "100"
})
Here is the playground with your example: https://mongoplayground.net/p/dPfH5fSOePq
did u try this ? const response = await Room.find({name: "100"})

How to find duplicate values in mongodb using distinct query?

I am working on Mongodb distinct query, i have one collection with repeated entry, i am doing as per the created_at. But i want to fetch without repeated values.
Sample JSON
{
"posts": [{
"id": "580a2eb915a0161010c2a562",
"name": "\"Ah Me Joy\" Porter",
"created_at": "15-10-2016"
}, {
"id": "580a2eb915a0161010c2a562",
"name": "\"Ah Me Joy\" Porter",
"created_at": "25-10-2016"
}, {
"id": "580a2eb915a0161010c2a562",
"name": "\"Ah Me Joy\" Porter",
"created_at": "01-10-2016"
}, {
"id": "580a2eb915a0161010c2bf572",
"name": "Hello All",
"created_at": "05-10-2016"
}]
}
Mongodb Query
db.getCollection('posts').find({"id" : ObjectId("580a2eb915a0161010c2a562")})
So i want to know about distinct query of mongodb, please kindly go through my post and let me know.
try as follows:
db.getCollection('posts').distinct("id")
It will return all the unique IDs in the collection posts as follows:
["580a2eb915a0161010c2a562", "580a2eb915a0161010c2bf572"]
From MongoDB docs:
The example use the inventory collection that contains the following documents:
{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }
To Return Distinct Values for a Field (dept):
db.inventory.distinct( "dept" )
The method returns the following array of distinct dept values:
[ "A", "B" ]
Reference:
https://docs.mongodb.com/v3.2/reference/method/db.collection.distinct/
As per my understanding, you want to get distinct results which should eliminates the duplicate id in that collection
By using distinct in mongodb, It will return list of distinct values
db.getCollection('posts').distinct("id");
["580a2eb915a0161010c2a562", "580a2eb915a0161010c2bf572"]
So you should look into mongodb aggregation
db.posts.aggregate(
{ "$group" : { "_id" : "$id", "name" : {"$first" : "$name"}, "created_at" : {"$first" : "$created_at"} }}
)
The output will be list of results which eliminates the duplicate id documents

Mongoose find anywhere inside document

i need to find record matching userId. the userId can be in any level of document.
It can be in parent level or it can be inside friends array.
[{
"_id": "543357620c9af6066e689713",
"createdDate": "2014-10-06 08:00 pm",
"cancle": false,
"eventDate": "2014/12/12",
"eventstatus": true,
"location": "chennai",
"userId": "54334def7e85de48638d1069",
"createdBy": "four",
"eventName": "jamba",
"__v": 0,
"friends": []
},
{
"_id": "543356fe0c9af6066e68970c",
"createdDate": "2014-10-06 07:59 pm",
"cancle": false,
"eventDate": "2014/12/12",
"eventstatus": true,
"location": "chennai",
"userId": "54310801e2659ecc3650100b",
"createdBy": "one",
"eventName": "tea ",
"__v": 0,
"friends": [
{
"userId": "54310814e2659ecc3650100c",
"userName": "two",
"phoneNumber": "22222222"
},
{
"userId": "54310945e2659ecc3650100d",
"userName": "three",
"phoneNumber": "33333333"
},
{
"userId": "54334def7e85de48638d1069",
"userName": "four",
"phoneNumber": "44444444"
}
]
}]
i am trying for long time. Any help is highly appreciated.
You need the $or operator. Also, you don't need to iterate to query for elements within an array. Assuming your collection is named Events:
Events.find({
$or: [
{ _id: req.params.userId },
{ 'friends.userId': req.params.userId }
]
}).exec();

Resources