Mongo DB : remove document from collection - mongodb

Here is one of my document of my collection "entities", I can't figure out how to remove it.
{
"_id" : {
"id" : "sensors:StreetLight2",
"type" : "sensors",
"servicePath" : "/egmmqttpath"
},
"attrNames" : [
"TimeInstant",
"PING_status"
],
"attrs" : {
"PING_status" : {
"value" : "delivered but no respond",
"type" : "string",
"md" : [
{
"name" : "TimeInstant",
"type" : "ISO8601",
"value" : "2015-11-20T09:02:53.114688"
}
],
"creDate" : 1448010161,
"modDate" : 1448010172
},
"TimeInstant" : {
"value" : "2015-11-20T09:02:53.114834",
"type" : "ISO8601",
"creDate" : 1448010122,
"modDate" : 1448010172
}
},
"creDate" : 1448010122,
"modDate" : 1448010172
}
Any ideas? how can I remove the above document? Thanks in advance.

From doc:
db.collection.remove()
Removes documents from a collection.
1) By _ID: Since _ID is unique.
db.entities.remove( {"_id" :
{
"id" : "sensors:StreetLight2",
"type" : "sensors",
"servicePath" : "/egmmqttpath"
}
})

I would pass the _id to remove it.
db.entities.remove({
"_id" : {
"id" : "sensors:StreetLight2",
"type" : "sensors",
"servicePath" : "/egmmqttpath"
}
})

remove document in mongodb
query = {"_id": <value of _id>}
db.entities.remove(query)

db.entities.remove(
"_id" : {
"id" : "sensors:StreetLight2",
"type" : "sensors",
"servicePath" : "/egmmqttpath""id" : "sensors:StreetLight2"
}
)
you can also take any key-value pair from documents for remove
you can refer these links for better understanding
https://docs.mongodb.org/manual/tutorial/remove-documents/
https://docs.mongodb.org/manual/reference/method/db.collection.remove/

In mongo shell you should use .remove():
db.entities.remove(
{
"_id" :
{
"id" : "sensors:StreetLight2",
"type" : "sensors",
"servicePath" : "/egmmqttpath"
}
})

Related

$lookup aggregation failed to display array value

I'm working with MongoDB and I've 2 collections.
data collection ["user-profile"]
{
"_id" : ObjectId("60650e6fc4b4603e1e78bb23"),
"firstName" : "Luthfan",
"lastName" : "Difiesa",
"mobile" : "86742633497",
"gender" : "male",
"createdOn" : ISODate("2021-04-22T05:26:07.428+0000"),
"updatedOn" : ISODate("2021-04-22T05:26:55.218+0000")
}
data collection ["user-wishlist"]
{
"_id" : ObjectId("60650e7a1a4a817a1dd0a29c"),
"userId" : "86742633497",
"contents" : [
{
"_id" : ObjectId("5ef9d2da228f840bbd41649c"),
"name" : "Kelas 11"
}
]
}
expected output:
{
"_id" : ObjectId("60650e6fc4b4603e1e78bb23"),
"firstName" : "Luthfan",
"lastName" : "Difiesa",
"mobile" : "86742633497",
"gender" : "male",
"contents" : [
{
"_id" : ObjectId("5ef9d2da228f840bbd41649c"),
"name" : "Kelas 11"
}
]
}
Here's the query:
db.getCollection("user-profile").aggregate(
[
{
"$lookup" : {
"from" : "user-wishlist",
"localField" : "mobile",
"foreignField" : "userId",
"as" : "contents"
}
}
],
{
"allowDiskUse" : false
}
);
But the result is like this:
{
"_id" : ObjectId("60650e6fc4b4603e1e78bb23"),
"firstName" : "Luthfan",
"lastName" : "Difiesa",
"mobile" : "86742633497",
"gender" : "male",
"contents" : [
]
}
is't because of collection name using special character or type data from foreign or localField? thank u...
Your query looks good, just need add a stage after lookup to achieve your desire result,
{
$addFields: {
contents: {
$arrayElemAt: ["$contents.contents", 0]
}
}
}
Playground

Update query on in the collection by "_id"

{
"_id" : "tenant/data/EMAIL/ENGLISH",
"tenantId" : "tenant2",
"channelType" : "EMAIL",
"template" : [
{
"_id" : "1",
"templateName" : "abc",
"effectiveStartDate" : ISODate("2017-01-01T12:00:00.000Z"),
"modifiedDate" : ISODate("2017-06-02T22:08:55.782Z"),
"active" : false
}
]
}
I need to update the "templateName" : "xyz" on the basis of "_id" : "tenant/data/EMAIL/ENGLISH"
I have tried these queries but got no success
db.getCollection('data').updateOne({"_id": "tenant/data/EMAIL/ENGLISH"},
{$set : { "template.$.templateName" : "XYZ"}}); 
db.getCollection('data').updateOne({"_id": "tenant/data/EMAIL/ENGLISH"},
{$set : { "template.templateName" : "XYZ"}}); 
Any help will be appreciated.
I have used positional-all operator to update the array.
Here is the query:
db.sample.update(
{
"_id": "tenant/data/EMAIL/ENGLISH"
},
{
$set:{
"template.$[].templateName":"XYZ"
}
}
)
Output
{
"_id" : "tenant/data/EMAIL/ENGLISH",
"tenantId" : "tenant2",
"channelType" : "EMAIL",
"template" : [
{
"_id" : "1",
"templateName" : "XYZ",
"effectiveStartDate" : ISODate("2017-01-01T12:00:00Z"),
"modifiedDate" : ISODate("2017-06-02T22:08:55.782Z"),
"active" : false
}
]
}
hope this will help :)

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]}}}
])

How do i remove array item from collection

How do i remove array item from collection in mongodb? Below is my structure.
{
"__v" : 12,
"_id" : ObjectId("52cc27daasdsc797ec7s8000001"),
"email" : "email#email.com",
"joindate" : ISODate("2014-01-07T16:14:18.158Z"),
"location" : "Canada",
"name" : "Albert",
"oauthID" : 58558855,
"myvideos" : [
{
"vid" : "wssEoGquzsiw1c",
"date" : ISODate("2014-06-01T05:28:32.713Z")
},
{
"vid" : "0_Vko7RXsdsmoI",
"date" : ISODate("2014-06-01T05:29:01.888Z")
},
{
"vid" : "ctbvhucsds050g",
"date" : ISODate("2014-06-01T05:29:27.395Z")
}
],
"username" : "myusername"
}
I would like to remove item vid (ctbvhucsds050g) from the myvideos array.
Appreciate any advice.
Found a solution to this.
db.users.update({"name":"Albert"}, {'$pull': {"myvideos": {"vid": "ctbvhucsds050g" }}});