mongodb find $elemMatch with Multiple Fields - mongodb

everyone. I need your help. For a script I have to search for users by their ldap id, but I have the problem that I get no output when searching.
a user has the following output.
db.users.find({"name" : "John Sample"} ).toArray()
[
{
"_id" : "testid",
"createdAt" : ISODate("2017-05-11T13:49:35.125Z"),
"services" : {
"password" : {
"bcrypt" : ""
},
"ldap" : {
"id" : "12345678",
"idAttribute" : "uid"
},
"resume" : {
"loginTokens" : [ ]
}
},
"username" : "john",
"emails" : [
{
"address" : "john.sample#test.com",
"verified" : true
}
],
"type" : "user",
"status" : "offline",
"active" : true,
"name" : "John Sample",
"_updatedAt" : ISODate("2018-07-05T18:44:22.061Z"),
"roles" : [
"user"
],
"ldap" : true,
"lastLogin" : ISODate("2018-07-05T10:33:00.712Z"),
"statusConnection" : "offline",
"utcOffset" : 2,
"statusDefault" : "offline"
}
]
I used this command but without success.
db.users.find({"services" : {"$elemMatch": {"ldap" : {"$elemMatch": {"id" : "12345678"}}}}}} ).toArray();
[ ]

$elemMatch is used to find elements that match criteria in an array. But services is an document (sub document), not an array. Just use dot notation to query :
db.users.find({"services.ldap.id":"12345678"})

Related

how to make mongodb aggregate with $in, $or $and

Here is Query in mongodb , where i used to get information on the basis of status, verify_status and their category as well as their Location, their is only one location for the field but need to find in multiple set of location.
Update : I try to run this query in Robo3t , it return blank Result but same query i run in Studio3t it shows expected Result. is there any version issue.
{
"status":{
"$eq":"Active"
},
"verify_status":{
"$eq":"Yes"
},
"$or":[
{
"category":{
"$eq":{
"$oid": "5da0f71e15712b5f7723bb58"
}
}
},
{
"multi_car_status":{
"$eq":"ON"
},
"additional_category":{
"$eq": "5da0f71e15712b5f7723bb58"
}
}
],
"driver_location":{
"$in":[
"5dee787f15712b443f6a5e06",
"5dee787f15712b443f6a5e06"
]
}
}
When i removed the driver_location or "$or" its return resul.there are
result in the db but it return return 0 result. i can't get the result with the both the operators. below is the sample data.
{
"_id" : ObjectId("5ead0f5f15712b5df22d7e23"),
"driver_location" : "5dee787f15712b443f6a5e06",
"category" : ObjectId("5da0f71e15712b5f7723bb58"),
"image" : "7f8e1ddfbe862a7ac4386b2f41fe953f.jpg",
"driver_name" : "Ravi aa",
"email" : "######gmail.com",
"dail_code" : "+1",
"mobile_number" : "83748746",
"dob" : "10/05/2000",
"password" : "######",
"verify_status" : "Yes",
"status" : "Active",
"availability" : "Yes",
"mode" : "Available",
"gender" : "male",
"vehicle_type" : null,
"vehicle_maker" : "5da0f05115712b5fb36e3d02",
"vehicle_model" : "5db22e1215712b25a36b8a3c",
"loc" : {
"lon" : 77.35124777,
"lat" : 28.6543715
},
"address" : {
"address" : "delhi",
"county" : "United States",
"state" : "AR",
"city" : "delhi",
"postal_code" : "122001"
},
"multi_car_status" : "ON",
"additional_category" : [
"5da09ed315712b413333ca58",
"5da0f6fc15712b5c1956eed6",
"5da0f73b15712b5fb36e3d09"
],
}

MongoDB $lookup on array of object

I have 2 collections structured as below. I have tried $lookup to get the result but I am not getting any result because of my local and foreign fields are in array of object.
Below is my structure:
{
"_id" : ObjectId("5795a3531d3f3afc19caefef"),
"name" : "category1",
"updatedAt" : "1469431592786",
"resources" : [
{
"_id" : ObjectId("5791be003fa3bedc15d3adde"),
"title" : "resource1",
"availability" : false
},
{
"_id" : ObjectId("5795a3771d3f3afc19caeff0"),
"title" : "resource2",
"availability" : true
}
]
}
Above "categories" schema have resources array of object. this resource _id is stored in bookings collection in following way:
"booking":
{
"_id" : ObjectId("57960aa8000ca7a46b7ef683"),
"name" : "1469491200000",
"__v" : 0,
"schedule" : [
{
"resourceId" : ObjectId("5791be003fa3bedc15d3adde"),
"userId" : ObjectId("5791be003fa3bedc15d3adcve"),
"title" : "grofep",
"_id" : ObjectId("57960aa8f9f9951c1fc923b1")
},
{
"resourceId" : ObjectId("5791be003fa3bedc15d3bddz"),
"userId" : ObjectId("5791be003fa3bedc15d3adcve"),
"title" : "mr3",
"_id" : ObjectId("57960aa8f9f9951c1fc923b2")
},
{
"resourceId" : ObjectId("5791be003fa3bedc15d3adde"),
"userId" : ObjectId("5791be003fa3bedc15d3adcve"),
"title" : "grofep23",
"_id" : ObjectId("57960aa8f9f9951c1fc923b3")
}
]
}
Now I want to get all the schedule of booking collection with their resource information.I want to fetch resources from categories table on the basis of booking schedule.
Desired output:
[
{
"name" : "1469491200000",
"resourceId" : ObjectId("5791be003fa3bedc15d3adde"),
"resourceTitle":"title",
"availability":false,
"bookings": [
{
"userId" : ObjectId("5791be003fa3bedc15d3adcve"),
"title" : "grofep",
"_id" : ObjectId("57960aa8f9f9951c1fc923b1")
},
{
"userId" : ObjectId("5791be003fa3bedc15d3adcve"),
"title" : "grofep23",
"_id" : ObjectId("57960aa8f9f9951c1fc923b3")
}
]
},
{
"name" : "1469491200000",
"resourceId" : ObjectId("5791be003fa3bedc15d3bddz"),
"resourceTitle":"mr3",
"availability":false,
"bookings": [
{
"userId" : ObjectId("5791be003fa3bedc15d3adcve"),
"title" : "mr3",
"_id" : ObjectId("57960aa8f9f9951c1fc923b2")
}
]
}
]
Help me to get this desired result.
Thanks.

Get document based on multiple criteria of embedded collection

I have the following document, I need to search for multiple items from the embedded collection"items".
Here's an example of a single SKU
db.sku.findOne()
{
"_id" : NumberLong(1192),
"description" : "Uploaded via CSV",
"items" : [
{
"_id" : NumberLong(2),
"category" : DBRef("category", NumberLong(1)),
"description" : "840 tag visual",
"name" : "840 Visual Mini Round",
"version" : NumberLong(0)
},
{
"_id" : NumberLong(7),
"category" : DBRef("category", NumberLong(2)),
"description" : "Maxi",
"name" : "Maxi",
"version" : NumberLong(0)
},
{
"_id" : NumberLong(11),
"category" : DBRef("category", NumberLong(3)),
"description" : "Button",
"name" : "Button",
"version" : NumberLong(0)
},
{
"_id" : NumberLong(16),
"category" : DBRef("category", NumberLong(4)),
"customizationFields" : [
{
"_class" : "CustomizationField",
"_id" : NumberLong(1),
"displayText" : "Custom Print 1",
"fieldName" : "customPrint1",
"listOrder" : 1,
"maxInputLength" : 12,
"required" : false,
"version" : NumberLong(0)
},
{
"_class" : "CustomizationField",
"_id" : NumberLong(2),
"displayText" : "Custom Print 2",
"fieldName" : "customPrint2",
"listOrder" : 2,
"maxInputLength" : 17,
"required" : false,
"version" : NumberLong(0)
}
],
"description" : "2 custom lines of farm print",
"name" : "Custom 2",
"version" : NumberLong(2)
},
{
"_id" : NumberLong(20),
"category" : DBRef("category", NumberLong(5)),
"description" : "Color Red",
"name" : "Red",
"version" : NumberLong(0)
}
],
"skuCode" : "NF-USDA-XC2/SM-BC-R",
"version" : 0,
"webCowOptions" : "840miniwithcust2"
}
There are repeat items.id throughout the embedded collection. Each Sku is made up of multiple items, all combinations are unique, but one item will be part of many Skus.
I'm struggling with the query structure to get what I'm looking for.
Here are a few things I have tried:
db.sku.find({'items._id':2},{'items._id':7})
That one only returns items with the id of 7
db.sku.find({items:{$all:[{_id:5}]}})
That one doesn't return anything, but it came up when looking for solutions. I found about it in the MongoDB manual
Here's an example of a expected result:
sku:{ "_id" : NumberLong(1013),
"items" : [ { "_id" : NumberLong(5) },
{ "_id" : NumberLong(7) },
{ "_id" : NumberLong(12) },
{ "_id" : NumberLong(16) },
{ "_id" :NumberLong(2) } ] },
sku:
{ "_id" : NumberLong(1014),
"items" : [ { "_id" : NumberLong(5) },
{ "_id" : NumberLong(7) },
{ "_id" : NumberLong(2) },
{ "_id" : NumberLong(16) },
{ "_id" :NumberLong(24) } ] },
sku:
{ "_id" : NumberLong(1015),
"items" : [ { "_id" : NumberLong(5) },
{ "_id" : NumberLong(7) },
{ "_id" : NumberLong(12) },
{ "_id" : NumberLong(2) },
{ "_id" :NumberLong(5) } ] }
Each Sku that comes back has both a item of id:7, and id:2, with any other items they have.
To further clarify, my purpose is to determine how many remaining combinations exist after entering the first couple of items.
Basically a customer will start specifying items, and we'll weed it down to the remaining valid combinations. So Sku.items[0].id=5 can only be combined with items[1].id=7 or items[1].id=10 …. Then items[1].id=7 can only be combined with items[2].id=20 … and so forth
The goal was to simplify my rules for purchase, and drive it all from the Sku codes. I don't know if I dug a deeper hole instead.
Thank you,
On the part of extracting the sku with item IDs 2 and 7, when I recall correctly, you have to use $elemMatch:
db.sku.find({'items' :{ '$all' :[{ '$elemMatch':{ '_id' : 2 }},{'$elemMatch': { '_id' : 7 }}]}} )
which selects all sku where there is each an item with _id 2 and 7.
You can use aggregation pipelines
db.sku.aggregate([
{"$unwind": "$sku.items"},
{"$group": {"_id": "$_id", "items": {"$addToSet":{"_id": "$items._id"}}}},
{"$match": {"items._id": {$all:[2,7]}}}
])

Query to filter the information from a mongodb collection

I have to retrieve a list of users from list of documents which matches the condition. The document structure look like below
{
"_id" : ObjectId("660ff865d4f9075d40a1101c"),
"orderFormId" : "OF-rJw4elBYK",
"orderDetails" : [
{
"courseId" : "53fc31f443fa1fe885d3ad61",
"userInfo" : [
{
"dob" : "2015-03-22T18:30:00.000Z",
"lastName" : "M",
"status" : "Pending Appproval",
"eMail" : "jihin345#baabte.com",
"firstName" : "Arun"
},
{
"status" : "requested",
"firstName" : "asdasd",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "asdafasd",
"userId" : "RQ-11xDPALgR",
"eMail" : "adsasd#baabte.com"
},
{
"status" : "requested",
"firstName" : "asdaf",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "fsdsdf",
"userId" : "RQ-OdoXAOLrB",
"eMail" : "ashdjasufh#baabte.com"
},
{
"status" : "requested",
"firstName" : "asdas",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "asdasd",
"userId" : "RQ-Bw2Xokmda",
"eMail" : "asdasd#gmail.com"
}
],
"userCount" : 5,
"Name" : "Compilers",
"coursePrice" : 1000,
"coursetype" : "offline"
},
{
"courseId" : "53fc31f443fa1fe885d3ad62",
"userInfo" : [
{
"dob" : "2015-03-22T18:30:00.000Z",
"lastName" : "Raj",
"status" : "requested",
"eMail" : "jihin432#baabte.com",
"firstName" : "Nithul"
},
{
"dob" : "2015-03-22T18:30:00.000Z",
"lastName" : "P C",
"status" : "requested",
"eMail" : "jihin345#baabte.com",
"firstName" : "Kahyoom"
}
],
"userCount" : 1,
"Name" : "Computer Science 101",
"coursePrice" : 0,
"coursetype" : "offline"
},
{
"courseId" : "57fc31f443fa1fe885d3ad64",
"userInfo" : [
{
"status" : "requested",
"firstName" : "asdasd",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "aasdasd",
"userId" : "RQ-WqEXBkjv5",
"eMail" : "asdasd#gmail.com"
}
],
"userCount" : 1,
"coursePrice" : 0,
"Name" : "Introduction to Haptics: Self-Paced",
"coursetype" : "offline"
}
],
"companyId" : ObjectId("54128cc57525614f6e3e710a"),
"createdDate" : ISODate("2015-03-23T11:26:29.027Z"),
"updatedDate" : ISODate("2015-03-24T15:00:33.248Z"),
"crmId" : ObjectId("660ab20bd4f9075d40a10d52"),
"urmId" : ObjectId("660ab20bd4f9075d40a10d52"),
"activeFlag" : 0,
"customCompanyCode" : "baa-106",
"status" : "Pending approval"}
From above document i have to get the users who have the status "Approved" in userInfo object which exists inside this document. I have created one query but this will output all the users who have different status.My query look like below,
db.clnTrainingRequest.find({companyId:ObjectId('54128cc57525614f6e3e710a'), "orderDetails.userInfo.status":{$in:['Approved']}}).toArray()
Please any one help me to sort out this issue
You can use aggregation. You need to $unwind orderDetails and the userInfo arrays and then use the $match to get users with status Approved
db.clnTrainingRequest.aggregate(
[ { "$match": { "companyId": ObjectId('54128cc57525614f6e3e710a') },
{ "$unwind": "$orderDetails" },
{ "$unwind": "$orderDetails.userInfo" },
{ "$match": { "orderDetails.userInfo.status": "Approved" }}
]
)

Two MongoDB queries same result, what is the difference?

I'm playing around with mongoDB and I can't figure out what is the difference between my two queries.
I use following collection:
{
"_id" : ObjectId("520b79869971eb1a0fdd0ad4"),
"created" : 1376483718636,
"updated" : 1376483718636,
"firstName" : "Jakob",
"lastName" : "D",
"email" : "jakob.d#test.com",
"emailValidated" : false,
"phoneNumber" : "",
"lastLogin" : 1376483718624,
"linkedProviders" : [
{
"userId" : "1XXXXXXXX6",
"providerId" : "facebook",
"password" : "",
"salt" : "",
"authMethod" : "oauth2",
"avatarUrl" : ""
}
],
"userRoles" : [
"ADMIN"
]
},
{
"_id" : ObjectId("520b7dd09971ebcd35dd0ad6"),
"created" : 1376484816666,
"updated" : 1376484816666,
"firstName" : "Jakob",
"lastName" : "D",
"email" : "jakob.d#test.com",
"emailValidated" : false,
"phoneNumber" : "",
"lastLogin" : 1376484816666,
"linkedProviders" : [
{
"userId" : "jakob.d#test.com",
"providerId" : "userpass",
"password" : "7e4aff9e0d90db2318ffcc689c11b66d",
"salt" : "N1GgNvy3NnS0i5GFDyglQZ9s4CeFNndn",
"authMethod" : "userPassword",
"avatarUrl" : ""
}
],
"userRoles" : [
"ADMIN"
]
}
The two queries that gives me the correct and same result(the one with objectId 520b79869971eb1a0fdd0ad4) are:
db.users.find({"linkedProviders.userId":"1XXXXXXXX6","linkedProviders.providerId":"facebook"})
db.users.find({"linkedProviders": {"$elemMatch": {"userId":"1XXXXXXXX6" },"$elemMatch": {"providerId":"facebook" }}})
So what is the difference between these two?
The difference is that $elemMatch finds items for one single array element.
This solution:
db.users.find({
"linkedProviders.userId": "1XXXXXXXX6",
"linkedProviders.providerId": "facebook"
})
Finds any user that has that userId and that providerId, but possibly in different items in linkedProviders, e.g., if linkedProviders[0].userId matches the first and linkedProviders[1].providerId matches the second part of the query, the full document (i.e., the user) will match that query.
On the other hand,
db.users.find({
"linkedProviders": {
"$elemMatch": {
"userId": "1XXXXXXXX6",
"providerId": "facebook"
}
}
})
will match only if the index values (0 and 1 in the previous example) are the same in the document, i.e., only if one array element matches both.
When there's only one key-value mapping in the $elemMatch, it should do the same as the query with the key-value mapping applied directly.
More information:
http://docs.mongodb.org/manual/reference/operator/elemMatch/#op._S_elemMatch