Posts

Showing posts with the label array

MongoDB tip: cursor.map

This is just a quick example of how we can use cursor.map to change the shape of the array. //push all the _id we found into an array, but the problem we have right now is how it's stored as array of documents while we are only interested in the value. var updateArray = db.getSiblingDB("equipment").needProcessedEquip.find({}, {_id: 1}).toArray(); updateArray; [     {         "_id" : "5680e9b8-6ffe-41bb-a035-e255ede87b8e"     },     {         "_id" : "08b08206-f2a7-49b8-bf7a-b72a6494e556"     },     {         "_id" : "17e49c0d-0892-4f4b-a0c5-effaaf07a058"     },     {         "_id" : "1b1756ce-63fe-4b9e-baf3-e2f418feb3d7"     },     {         "_id" : "e31a02f6-e217-4172-bcf5-684ab40321de"     },     {         "_id" : "01f6fcab-4123-44aa-a...

MongoDB tip: Using the positional $ operator in array

This post is a quick documentation on how to update elements in arrays using positional operator to look for the value to update. Let's setting up our example: db.movies.insertMany( [ { "title" : "Batman" , "category" : [ "action" , "adventure" ], "imdb_rating" : 7.6 , "budget" : 35 }, { "title" : "Godzilla" , "category" : [ "action" , "adventure" , "sci-fi" ], "imdb_rating" : 6.6 }, { "title" : "Home Alone" , "category" : [ "family" , "comedy" ], "imdb_rating" : 7.4 } ]) From MongoDB documentation: The positional $ operator $ is a positional operator that specifies an element in an array to update. It acts as a placeholder for the first element that matches the query document.  $ replaces the element in...

MongoDB tip: comparing field cross collection using python

Image
The goal is to find anything that's in col2, but not in col1. col1 contains the following col2 contains the following Note, the field to compare in both collection need not to be in order as seen in the images. Again, I am trying to find what's missing in the first set from the second set.  from pymongo import MongoClient import bson client=MongoClient(host="mongodb://10.155.228.75:21001") db=client.testJoe col1=db.col1.distinct("compID"); col2= db.col2.distinct("compID"); col1= [int(x) for x in col1] x = set(col2) - set(col1) print(int(list(x)[0])) we see the output is 7, which is the missing number from col1

MongoDB query sample: using $unwind

This is the sample collection I am using in this example: db.getCollection('testCol').find({}).pretty() {     "_id" : ObjectId("59764121cd6857bf00a34809"),     "a" : 1,     "b" : 1 } {     "_id" : ObjectId("59764126cd6857bf00a3480a"),     "a" : 2,     "b" : 2 } {     "_id" : ObjectId("5976412ccd6857bf00a3480b"),     "a" : 3,     "b" : 3 } {     "_id" : ObjectId("59764294cd6857bf00a3480c"),     "a" : 4,     "b" : 4,     "arr" : [         {             "a" : 6,             "b" : 6         },         {             "a" : 7,             "b" : 7         }     ] } This will give me the number of element inside of the arr...