Below is the schema for an array contacts. The contacts array has a field hashtag which is another array. How do I find all the contacts which have a particular hashtag? For example all contacts with hashtag "zxc"?
"contacts" : [
{
"addedDate" : ISODate("2015-12-02T09:06:09.891Z"),
"personEmailId" : "tell.fadgfdg#gmail.com",
"_id" : ObjectId("565eb481bf35eeb83d7f9f13"),
"verified" : true,
"favorite" : true,
"linkedinUserName" : null,
"facebookUserName" : null,
"twitterUserName" : "IamlifePaul",
"count" : 2,
"relationshipStrength_updated" : 0,
"contactRelation" : {
"decisionmaker_influencer" : null,
"prospect_customer" : "prospect"
},
"source" : "abc",
"mobileNumber" : "3546789",
"skypeId" : "123",
"designation" : "test",
"companyName" : "Something",
"location" : "Hyderabad, Telangana, India",
"personName" : "Naveen Paul",
"personId" : "565022d7dbeaeb9e17fc7083",
"hashtag" : [
"latestTag",
"anotherTag",
"#hash",
"openLove",
"hellTwo",
"working?",
"hello",
"lol",
"zxc"
],
"lastInteracted" : ISODate("2015-12-08T05:07:53.746Z")
},
{
"addedDate" : ISODate("2015-12-02T09:06:09.891Z"),
"personEmailId" : "naveenpaul.fadgfdg#gmail.com",
"_id" : ObjectId("565eb481bf35eeb83d7f9f13"),
"verified" : true,
"favorite" : true,
"linkedinUserName" : null,
"facebookUserName" : null,
"twitterUserName" : "IamlifePaul",
"count" : 2,
"relationshipStrength_updated" : 0,
"contactRelation" : {
"decisionmaker_influencer" : null,
"prospect_customer" : "prospect"
},
"source" : "abc",
"mobileNumber" : "3546789",
"skypeId" : "123",
"designation" : "test",
"companyName" : "Something",
"location" : "Hyderabad, Telangana, India",
"personName" : "Naveen Paul",
"personId" : "565022d7dbeaeb9e17fc7083",
"hashtag" : [
"latestTag",
"anotherTag",
"#hash",
"openLove",
"hellTwo",
"working?",
"hello",
"lol",
"zxc"
],
"lastInteracted" : ISODate("2015-12-08T05:07:53.746Z")
},
{
"addedDate" : ISODate("2015-12-02T09:06:09.891Z"),
"personEmailId" : "naveenpaul.fadgfdg#gmail.com",
"_id" : ObjectId("565eb481bf35eeb83d7f9f13"),
"verified" : true,
"favorite" : true,
"linkedinUserName" : null,
"facebookUserName" : null,
"twitterUserName" : "IamlifePaul",
"count" : 2,
"relationshipStrength_updated" : 0,
"contactRelation" : {
"decisionmaker_influencer" : null,
"prospect_customer" : "prospect"
},
"source" : "abc",
"mobileNumber" : "3546789",
"skypeId" : "123",
"designation" : "test",
"companyName" : "Something",
"location" : "Hyderabad, Telangana, India",
"personName" : "Naveen Paul",
"personId" : "565022d7dbeaeb9e17fc7083",
"hashtag" : [
"polly",
"tagger",
"#hash",
"working?",
"hello",
"lol",
"zxc"
],
"lastInteracted" : ISODate("2015-12-08T05:07:53.746Z")
}
I did this query - db.myColl.find({"contacts.hashtag":"zxc"},{"contacts":{$elemMatch:{"hashtag":"zxc"}}}).pretty()
which returned only one contact. I need to get all contacts.
You can do it via aggregation framework:
1) Do an initial match to reduce the input set for aggregation
2) Unwind contacts field.
3) Filter out contacts with hashtag 'zxc'
4) Group by id and put contacts on "contacts" field.
db.getCollection('contacts').aggregate([
{$match: {"contacts.hashtag":"zxc"}},
{$unwind: "$contacts"},
{$match: {"contacts.hashtag":"zxc"}},
{$group: {_id:"$_id", "contacts": {$push:"$contacts"}}}
])
You can use
For multiple hashtag in single doc
db.myColl.find({"contacts.hashtag":{$in : ['zxc','anotherTag']}});
//will return all doc with any of the two hashtags.
For single hashtag
db.myColl.find({"contacts.hashtag":'zxc'});
//return all documents with hashtag 'zxc'
Please refer $in
Related
Good day all,
I have a set of documents which are hitting the BSON size limit due to the number of items in an array of Subdocuments. I'm trying to apply a new field to these subdocuments as part of a schema update but it's failing on these specific documents because the new field pushes the BSON size limit over.
What I want to do is effectively split the Document(s) in 'half' based on the array of subdocuments, so I would have Document1 (the original) with the array now containing (for example) subdocuments 1-2, and Document1B having the array containing 3-4.
Here is an example of the basic layout
{
"_id" : ObjectId("5f11d4c28663f32e940696e0"),
"DocumentId" : "0000001",
"Items" : [
{
"ItemId" : NumberInt(1),
"ItemType" : NumberInt(1),
"ClassType" : "1",
"Created" : ISODate("2012-03-13T11:13:22.000+0000"),
"LastUpdated" : ISODate("2020-03-12T15:52:39.000+0000")
},
{
"ItemId" : NumberInt(2),
"ItemType" : NumberInt(1),
"ClassType" : "1",
"Created" : ISODate("2012-03-13T11:13:22.000+0000"),
"LastUpdated" : ISODate("2020-03-12T15:52:39.000+0000")
},
{
"ItemId" : NumberInt(3),
"ItemType" : NumberInt(1),
"ClassType" : "1",
"Created" : ISODate("2012-03-13T11:13:22.000+0000"),
"LastUpdated" : ISODate("2020-03-12T15:52:39.000+0000")
},
{
"ItemId" : NumberInt(4),
"ItemType" : NumberInt(1),
"ClassType" : "1",
"Created" : ISODate("2012-03-13T11:13:22.000+0000"),
"LastUpdated" : ISODate("2020-03-12T15:52:39.000+0000")
},
],
"Priority" : NumberInt(0),
"Status" : NumberInt(3),
"FileChecksum" : "ca1fbd9c8e1669bcf4155657d3600fa4",
"CreatedBy" : "anonymous.user#test.com",
"LastUpdatedBy" : null,
"AssignedBy" : "anonymous.user#test.com",
"DeletedBy" : null,
"LastUpdated" : ISODate("2020-03-12T15:52:39.000+0000"),
"Created" : ISODate("2012-03-13T08:13:23.000+0000"),
"Assigned" : ISODate("2012-03-13T11:10:48.000+0000"),
"Completed" : ISODate("2012-03-13T11:13:22.000+0000"),
"DeletedDate" : null,
"AssignedTo" : "anonymous.user#test.com",
"RejectionReason" : null,
"Deleted" : false,
"DeletionReason" : null
}
I am trying to do a transformation from one data structure to another and am using NoSQL Booster as I feel more comfortable using SQL queries than I do using Mongo script, a little lazy but its worked for me thus far.
I have a document which has a an array of line items which represents a sales receipt. The line items are the items sold.
I have used the following SQL query to generate Mongo script to select and then rename values from one document to create another. Where I'm stuck is in selecting from an array some fields and renaming them into a new document within a new array.
mb.runSQLQuery(`
SELECT object_origin,
party_uuid AS company,
connection_uuid AS connection,
object_created AS object_creation_date,
"object_raw_origin_data.register_sales.sale_date" AS transaction_date,
"object_raw_origin_data.register_sales.total_price"
+ "object_raw_origin_data.register_sales.total_tax" AS transaction_gross_value,
"object_raw_origin_data.register_sales.total_price" AS transaction_net_value,
'goods-service-transaction' AS object_class,
'point-of-sale' AS object_origin_category,
'offline' AS object_origin_type,
object_origin AS object_origin,
"object_raw_origin_data.register_sales.invoice_number" AS transaction_reference,
"object_raw_origin_data.register_sales.status" AS transaction_status,
'GBP' AS transaction_currency,
"object_raw_origin_data.register_sales.sale_products.name" AS 'line_items.item_name'
FROM Vend_raw_transactions
`)
The query above works all except the last line which creates an object in the document called line_items but it isn't an array. The source is also an array.
Below is the Mongo script it creates for me:
db.Vend_raw_transactions.aggregate(
[{
"$project": {
"object_origin": "$object_origin",
"company": "$party_uuid",
"connection": "$connection_uuid",
"object_creation_date": "$object_created",
"transaction_date": "$object_raw_origin_data.register_sales.sale_date",
"transaction_gross_value": {
"$add": [
"$object_raw_origin_data.register_sales.total_price",
"$object_raw_origin_data.register_sales.total_tax"
]
},
"transaction_net_value":
"$object_raw_origin_data.register_sales.total_price",
"object_class": "goods-service-transaction",
"object_origin_category": "point-of-sale",
"object_origin_type": "offline",
"transaction_reference":
"$object_raw_origin_data.register_sales.invoice_number",
"transaction_status": "$object_raw_origin_data.register_sales.status",
"transaction_currency": "GBP",
"line_items.item_name":
"$object_raw_origin_data.register_sales.sale_products.name"
}
}])
Does anyone know why the last line isn't working for me?
"line_items.item_name": "$object_raw_origin_data.register_sales.sale_products.name"
I'm pretty sure I'm missing an [*] somewhere. Thanks, Matt
EDITED TO ADD example of Vend Transaction
{
"object_category" : "application",
"object_type" : "register-sales-24-months",
"object_origin" : "vend",
"tenant_uuid" : "00000000-0000-0009-9999-999999999999",
"party_uuid" : "8d519765-05d2-469f-ad35-d7a22fa9df2f",
"subscription_uuid" : "0",
"connection_uuid" : "6ed9bd79-d9c5-4296-a821-7e15b1c69e6c",
"status" : "",
"object_created" : ISODate("2018-03-15T21:40:57.158+0000"),
"object_raw_origin_data" : {
"pagination" : {
"results" : NumberInt(75964),
"page" : NumberInt(1),
"page_size" : NumberInt(200),
"pages" : NumberInt(380)
},
"register_sales" : {
"id" : "776a66f2-993c-b372-11e8-26f9bbe253f4",
"source" : "USER",
"source_id" : "",
"register_id" : "02dcd191-ae55-11e6-edd8-ec8dce1d9e1c",
"market_id" : "3",
"customer_id" : "02d59481-b67d-11e5-f667-b08185e8f6d5",
"customer_name" : "",
"customer" : {
"id" : "02d59481-b67d-11e5-f667-b08185e8f6d5",
"name" : "",
"customer_code" : "WALKIN",
"customer_group_id" : "02d59481-b67d-11e5-f667-b08185e893f8",
"customer_group_name" : "All Customers",
"updated_at" : "2016-01-01 12:16:44",
"deleted_at" : "",
"balance" : "0",
"year_to_date" : "0",
"date_of_birth" : "",
"sex" : "",
"custom_field_1" : "",
"custom_field_2" : "",
"custom_field_3" : "",
"custom_field_4" : "",
"note" : "",
"contact" : {
}
},
"user_id" : "02d59481-b655-11e5-f667-dca974edc4ea",
"user_name" : "Alvaro Velosa",
"sale_date" : "2018-03-13 20:04:57",
"created_at" : "2018-03-13 20:05:08",
"updated_at" : "2018-03-13 20:05:08",
"total_price" : 3.5,
"total_cost" : 2.74,
"total_tax" : NumberInt(0),
"tax_name" : "No Tax",
"note" : "",
"status" : "CLOSED",
"short_code" : "newa6f",
"invoice_number" : "Masonic2107Temple",
"accounts_transaction_id" : "",
"return_for" : "",
"register_sale_products" : [
{
"id" : "776a66f2-993c-b372-11e8-26f9cbf10f10",
"product_id" : "02dcd191-ae55-11e7-f130-9d4f4bcd91b1",
"register_id" : "02dcd191-ae55-11e6-edd8-ec8dce1d9e1c",
"sequence" : "0",
"handle" : "LAGERDRAUGHT300",
"sku" : "10287",
"name" : "LAGER DRAUGHT £3.00",
"quantity" : NumberInt(1),
"price" : 3.5,
"cost" : 2.74,
"price_set" : NumberInt(0),
"discount" : NumberInt(0),
"loyalty_value" : NumberInt(0),
"tax" : NumberInt(0),
"tax_id" : "02d59481-b67d-11e5-f667-b08185ec2871",
"tax_name" : "No Tax",
"tax_rate" : NumberInt(0),
"tax_total" : NumberInt(0),
"price_total" : 3.5,
"display_retail_price_tax_inclusive" : "0",
"status" : "CONFIRMED",
"attributes" : [
{
"name" : "line_note",
"value" : ""
}
]
}
],
"totals" : {
"total_tax" : NumberInt(0),
"total_price" : 3.5,
"total_payment" : 3.5,
"total_to_pay" : NumberInt(0)
},
"register_sale_payments" : [
{
"id" : "776a66f2-993c-b372-11e8-26f9cd75e9aa",
"payment_type_id" : "1",
"register_id" : "02dcd191-ae55-11e6-edd8-ec8dce1d9e1c",
"retailer_payment_type_id" : "02d59481-b655-11e5-f667-b0a23bc0e7bc",
"name" : "Cash",
"label" : "Account Customer",
"payment_date" : "2018-03-13 20:04:57",
"amount" : NumberInt(10)
},
{
"id" : "776a66f2-993c-b372-11e8-26f9cd7a3096",
"payment_type_id" : "1",
"register_id" : "02dcd191-ae55-11e6-edd8-ec8dce1d9e1c",
"retailer_payment_type_id" : "02d59481-b655-11e5-f667-b0a23bc0e7bc",
"name" : "Cash",
"label" : "Account Customer",
"payment_date" : "2018-03-13 20:04:57",
"amount" : -6.5
}
]
}
}
}
Use the $map operator to shape the field to an array by mapping the array elements to the item_name key:
"line_items": {
"$map": {
"input": "$object_raw_origin_data.register_sales.register_sale_products",
"as": "product",
"in": { "item_name": "$$product.name" }
}
}
Output
"line_items" : [
{
"item_name" : "LAGER DRAUGHT £3.00"
}
]
in my sails controller I have implement a function to find users. but when I try to search using ObjectId it returns all the data. I couldn't find any reason. but it works when I create a new separate field as "userID", and find using "userID". I think the problem is find using the "ObjectId" what could be the issue.
module.exports = {
updateOrders : function(req,res){
var ObjectId = require('mongodb').ObjectID;
console.log("req " + req);
var data = req.body;
var obj = [];
console.log("\ndata "+(data));
var jdata = JSON.stringify(data);
console.log("\njdata: "+jdata);
data.forEach(function(orders){
var objid = ObjectId(orders.id);
console.log("Obj orders id :" + objid);
ApplicationOrder.find({id: ObjectId(orders.id)}).exec(function (err, order) {
if (err){
return done(err);
}
console.log('order ' + order);
obj.push(order);
});
})
res.send(obj);
}
};
Json data: printed in the console.
{
"_id" : ObjectId("59a8f820caf1cae37af72c0c"),
"appId" : "59a669431954a69e37c20b69",
"registeredUser" : "59a677811954a69e37c20b73",
"item" : [
{
"id" : "59a669441954a69e37c20b70",
"name" : "Short x",
"qty" : 1,
"sku" : "1111",
"totWeight" : null,
"price" : "250",
"total" : "250",
"imgURL" : [
{
"img" : "short_x.png"
}
],
"totalQty" : 218
}
],
"amount" : "250",
"customerName" : "dilakshan",
"deliverName" : "dilakshan",
"deliveryNo" : "11010",
"deliveryStreet" : "delgoda",
"deliveryCity" : "kandana",
"deliveryCountry" : "Sri Lanka",
"deliveryZip" : "11010",
"telNumber" : 94779967409,
"tax" : "0",
"shippingCost" : "0",
"shippingOpt" : "Flat Rate",
"email" : "s.dilakshan#yahoo.com",
"currency" : "$",
"paymentStatus" : "Pending",
"fulfillmentStatus" : "Pending",
"createdAt" : ISODate("2017-09-01T06:03:12.584Z"),
"updatedAt" : ISODate("2017-09-01T06:03:12.584Z")
}
{
"_id" : ObjectId("59a8f82fcaf1cae37af72c0d"),
"appId" : "59a669431954a69e37c20b69",
"registeredUser" : "59a677811954a69e37c20b73",
"item" : [
{
"id" : "59a669441954a69e37c20b6d",
"name" : "Shirt x",
"qty" : 1,
"sku" : "1111",
"totWeight" : null,
"price" : "250",
"total" : "250",
"imgURL" : [
{
"img" : "shirt_x.png"
}
],
"totalQty" : 244
}
],
"amount" : "250",
"customerName" : "dilakshan",
"deliverName" : "dilakshan",
"deliveryNo" : "11010",
"deliveryStreet" : "delgoda",
"deliveryCity" : "kandana",
"deliveryCountry" : "Sri Lanka",
"deliveryZip" : "11010",
"telNumber" : 94779967409,
"tax" : "0",
"shippingCost" : "0",
"shippingOpt" : "Flat Rate",
"email" : "s.dilakshan#yahoo.com",
"currency" : "$",
"paymentStatus" : "Pending",
"fulfillmentStatus" : "Pending",
"createdAt" : ISODate("2017-09-01T06:03:27.022Z"),
"updatedAt" : ISODate("2017-09-01T06:03:27.022Z")
}
{
"_id" : ObjectId("59a8f83ecaf1cae37af72c0e"),
"appId" : "59a669431954a69e37c20b69",
"registeredUser" : "59a677811954a69e37c20b73",
"item" : [
{
"id" : "59a669441954a69e37c20b71",
"name" : "Beach Suit",
"qty" : 2,
"sku" : "1111",
"totWeight" : null,
"price" : "250",
"total" : "250",
"imgURL" : [
{
"img" : "cloth3.png"
}
],
"totalQty" : 238
}
],
"amount" : "500",
"customerName" : "dilakshan",
"deliverName" : "dilakshan",
"deliveryNo" : "11010",
"deliveryStreet" : "delgoda",
"deliveryCity" : "kandana",
"deliveryCountry" : "Sri Lanka",
"deliveryZip" : "11010",
"telNumber" : 94779967409,
"tax" : "0",
"shippingCost" : "0",
"shippingOpt" : "Flat Rate",
"email" : "s.dilakshan#yahoo.com",
"currency" : "$",
"paymentStatus" : "Pending",
"fulfillmentStatus" : "Pending",
"createdAt" : ISODate("2017-09-01T06:03:42.439Z"),
"updatedAt" : ISODate("2017-09-01T06:03:42.439Z")
}
For standard sails.js/waterline queries, you have to use the id as a String in your query params, do not use ObjectId(ordersId).
When you use a sails native query, use ObjectId(ordersId).
If you are using any mongodb adapter then do not try to convert id by ObjectId(orders.id).Try normal query like
ApplicationOrder.find({'id':orders.id})
For native sails query,you have to convert id to objectId.
I finally was able to fix the issue. I had to edit the my model class in sails and use only orders.id model class,
_id:{type : 'objectid'} and when search
.find({_id: orders.id})
this worked for me perfectly.
I am having a collection orders , inside collection I am having attributes Array , I want to group the records on attributes.value where attributes.name is "sugery"
db.orders.find({},{"attributes":1}).sort({_id:-1}).limit(3);
{
"_id" : ObjectId("599cfdb0f6ec8d00015b0880"),
"attributes" : [
{
"id" : ObjectId("5979a220ad86210001997d5a"),
"name" : "patient",
"status" : NumberInt(1),
"sysDefined" : NumberInt(1),
"value" : "Lincon Burrows"
},
{
"id" : ObjectId("5979a229ad86210001997d5c"),
"name" : "notes",
"status" : NumberInt(1),
"sysDefined" : NumberInt(1),
"value" : ""
},
{
"id" : ObjectId("5979a230ad86210001997d5e"),
"name" : "surgeon",
"status" : NumberInt(1),
"sysDefined" : NumberInt(1),
"value" : "Dr. Williams"
},
{
"id" : ObjectId("5979a238ad86210001997d60"),
"name" : "surgery",
"status" : NumberInt(1),
"sysDefined" : NumberInt(1),
"value" : "Heart Surgery"
}
]
}
{
"_id" : ObjectId("599c357a9ec26c00017892a6"),
"attributes" : [
{
"value" : "new patient",
"sysDefined" : NumberInt(1),
"status" : NumberInt(1),
"name" : "patient",
"id" : ObjectId("5979a220ad86210001997d5a")
},
{
"value" : "",
"sysDefined" : NumberInt(1),
"status" : NumberInt(1),
"name" : "notes",
"id" : ObjectId("5979a229ad86210001997d5c")
},
{
"value" : "http://localhost:4200/#new surgeon",
"sysDefined" : NumberInt(1),
"status" : NumberInt(1),
"name" : "surgeon",
"id" : ObjectId("5979a230ad86210001997d5e")
},
{
"value" : "new surgery",
"sysDefined" : NumberInt(1),
"status" : NumberInt(1),
"name" : "surgery",
"id" : ObjectId("5979a238ad86210001997d60")
}
]
}
{
"_id" : ObjectId("599c2069b2afd900019ea142"),
"attributes" : [
{
"value" : "Mellisa Darwin",
"sysDefined" : NumberInt(1),
"status" : NumberInt(1),
"name" : "patient",
"id" : ObjectId("5979a220ad86210001997d5a")
},
{
"value" : "",
"sysDefined" : NumberInt(1),
"status" : NumberInt(1),
"name" : "notes",
"id" : ObjectId("5979a229ad86210001997d5c")
},
{
"value" : "Dr. Josefina P. Robles",
"sysDefined" : NumberInt(1),
"status" : NumberInt(1),
"name" : "surgeon",
"id" : ObjectId("5979a230ad86210001997d5e")
},
{
"value" : "Spine Surgery",
"sysDefined" : NumberInt(1),
"status" : NumberInt(1),
"name" : "surgery",
"id" : ObjectId("5979a238ad86210001997d60")
}
]
}
I want output like
[
{
"_id":"Heart Surgery",
"count":1
},
{
"_id":"new surgery",
"count":1
},
{
"_id":"Spine Surgery",
"count":1
}
]
Try this :
orders.aggregate({"attributes":1}, {$unwind:"$attributes"},{$match:{"attributes.name":"surgery"}})
please see mongodb documentation for group. db.collection.group()
The following are examples of the db.collection.group() method. The examples assume an orders collection with documents of the following prototype:
{
_id: ObjectId("5085a95c8fada716c89d0021"),
ord_dt: ISODate("2012-07-01T04:00:00Z"),
ship_dt: ISODate("2012-07-02T04:00:00Z"),
item: {
sku: "abc123",
price: 1.99,
uom: "pcs",
qty: 25
}
}
Group by Two Fields
The following example groups by the ord_dt and item.sku fields those documents that have ord_dt greater than 01/01/2012:
db.runCommand({
group:
{
ns: 'orders',
key: { ord_dt: 1, 'item.sku': 1 },
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
$reduce: function ( curr, result ) { },
initial: { }
}
})
Below is the schema for an array contacts. The contacts array has a field hashtag which is another array. How do I delete an element openLove from the array Hashtags?
"contacts" : [
{
"addedDate" : ISODate("2015-12-02T09:06:09.891Z"),
"personEmailId" : "tell.fadgfdg#gmail.com",
"_id" : ObjectId("565eb481bf35eeb83d7f9f13"),
"verified" : true,
"favorite" : true,
"linkedinUserName" : null,
"facebookUserName" : null,
"twitterUserName" : "IamlifePaul",
"count" : 2,
"relationshipStrength_updated" : 0,
"contactRelation" : {
"decisionmaker_influencer" : null,
"prospect_customer" : "prospect"
},
"source" : "abc",
"mobileNumber" : "3546789",
"skypeId" : "123",
"designation" : "test",
"companyName" : "Something",
"location" : "Hyderabad, Telangana, India",
"personName" : "Naveen Paul",
"personId" : "565022d7dbeaeb9e17fc7083",
"hashtag" : [
"latestTag",
"anotherTag",
"#hash",
"openLove",
"hellTwo",
"working?",
"hello",
"lol",
"zxc"
],
"lastInteracted" : ISODate("2015-12-08T05:07:53.746Z")
},
{
"addedDate" : ISODate("2015-12-02T09:06:09.891Z"),
"personEmailId" : "naveenpaul.fadgfdg#gmail.com",
"_id" : ObjectId("565eb481bf35eeb83d7f9f13"),
"verified" : true,
"favorite" : true,
"linkedinUserName" : null,
"facebookUserName" : null,
"twitterUserName" : "IamlifePaul",
"count" : 2,
"relationshipStrength_updated" : 0,
"contactRelation" : {
"decisionmaker_influencer" : null,
"prospect_customer" : "prospect"
},
"source" : "abc",
"mobileNumber" : "3546789",
"skypeId" : "123",
"designation" : "test",
"companyName" : "Something",
"location" : "Hyderabad, Telangana, India",
"personName" : "Naveen Paul",
"personId" : "565022d7dbeaeb9e17fc7083",
"hashtag" : [
"latestTag",
"anotherTag",
"#hash",
"openLove",
"hellTwo",
"working?",
"hello",
"lol",
"zxc"
],
"lastInteracted" : ISODate("2015-12-08T05:07:53.746Z")
},
{
"addedDate" : ISODate("2015-12-02T09:06:09.891Z"),
"personEmailId" : "naveenpaul.fadgfdg#gmail.com",
"_id" : ObjectId("565eb481bf35eeb83d7f9f13"),
"verified" : true,
"favorite" : true,
"linkedinUserName" : null,
"facebookUserName" : null,
"twitterUserName" : "IamlifePaul",
"count" : 2,
"relationshipStrength_updated" : 0,
"contactRelation" : {
"decisionmaker_influencer" : null,
"prospect_customer" : "prospect"
},
"source" : "abc",
"mobileNumber" : "3546789",
"skypeId" : "123",
"designation" : "test",
"companyName" : "Something",
"location" : "Hyderabad, Telangana, India",
"personName" : "Naveen Paul",
"personId" : "565022d7dbeaeb9e17fc7083",
"hashtag" : [
"polly",
"tagger",
"#hash",
"working?",
"hello",
"lol",
"zxc"
],
"lastInteracted" : ISODate("2015-12-08T05:07:53.746Z")
}
How do I delete an element from the array Hashtags?
for example remove openLove?
You would normally do this using the positional operator $ as follows:
db.collection.update(
{ "contacts.hashtag": "openLove" },
{
"$pull": {
"contacts.$.hashtag": "openLove"
}
}
)
However, as this only supports one-level deep arrays (the positional $ operator acts as a placeholder for the first element that matches the query document), only the first element that matches the query document is removed. There is a JIRA trackable for this here: https://jira.mongodb.org/browse/SERVER-831
If you know the index of the hashtags array that has the elememt to be removed beforehand then the update query will be:
db.collection.update(
{ "contacts.hashtag": "openLove" },
{
"$pull": {
"contacts.0.hashtag": "openLove",
"contacts.1.hashtag": "openLove"
}
}
)
Consider redesigning your schema to avoid nested arrays so that you can normalize your collection by creating a separate contacts collection where each document represents a contact, with information common to a set of contacts duplicated in the original collection. Something like the following:
collection schema:
{
_id: collection_id,
contacts: [
ObjectId("565eb481bf35eeb83d7f9f13"),
ObjectId("565eb481bf35eeb83d7f9f14"),
ObjectId("565eb481bf35eeb83d7f9f15")
]
}
contacts schema:
{
"addedDate" : ISODate("2015-12-02T09:06:09.891Z"),
"personEmailId" : "tell.fadgfdg#gmail.com",
"_id" : ObjectId("565eb481bf35eeb83d7f9f13"),
...
"hashtag" : [
"latestTag",
"anotherTag",
"#hash",
"openLove",
"hellTwo",
"working?",
"hello",
"lol",
"zxc"
],
"lastInteracted" : ISODate("2015-12-08T05:07:53.746Z")
},
{
"addedDate" : ISODate("2015-12-02T09:06:09.891Z"),
"personEmailId" : "naveenpaul.fadgfdg#gmail.com",
"_id" : ObjectId("565eb481bf35eeb83d7f9f14"),
...
"hashtag" : [
"latestTag",
"anotherTag",
"#hash",
"openLove",
"hellTwo",
"working?",
"hello",
"lol",
"zxc"
],
"lastInteracted" : ISODate("2015-12-08T05:07:53.746Z")
},
{
"addedDate" : ISODate("2015-12-02T09:06:09.891Z"),
"personEmailId" : "naveenpaul.eewsdf#gmail.com",
"_id" : ObjectId("565eb481bf35eeb83d7f9f15"),
...
"hashtag" : [
"polly",
"tagger",
"#hash",
"working?",
"hello",
"lol",
"zxc"
],
"lastInteracted" : ISODate("2015-12-08T05:07:53.746Z")
}
Updating the contacts collection would be easier, simply run the operation
db.contacts.update(
{ "hashtag": "openLove" },
{
"$pull": { "hashtag": "openLove" }
}
)
If redesigning the schema is out of your scope then you would need a mechanism to dynamically generate the update document i.e. create the $pull object on the fly. Consider using Map-Reduce to generate that, this answer details the whole operation concept.
With the help of chridam's answer, I got it to work by using the object Id of each contact.
db.user.update(
{ "contacts._id": ObjectId("5680f392e623e8b2107e6465") },
{
"$pull": {
"contacts.$.hashtag": "openLove"
}
})
This is almost what I need, however the $ positional indicator only matches the FIRST top level array element, and my scenario includes the possibility (just like the OP) that the value we want to remove can occur in multiple index positions.
To remove the value from ALL top level array elements, use this instead:
db.user.update(
{ "contacts._id": ObjectId("5680f392e623e8b2107e6465") },
{
"$pull": {
"contacts.$[].hashtag": "openLove"
}
})