2

For the following Json file, I have a mongodb query to select "Car" part of document only:

db.collection.find({_item:"Home"}, {"Car":1, "_id":0})

How do I write this query in Powershell?

{
   "_id" : 1,
   "_item": "Home",
   "Car": [
    {"name": "BMW", "model": "series 3"},
    {"name": "Audi", "model": "A4"}
   ],
   "Fruit": [
    {"name": "Banana", "color": "Yellow"},
    {"name": "Apple", "color": "Red"}
   ]
 }

2 Answers 2

3
$databaseName = "database"
$collectionName = "collection"
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017"
$server = $client.GetServer()
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)

$query = MongoDB.Driver.Builders.Query.EQ("_item","HOME")
$results = $collection.Find($query).SetFields(Fields.Exclude("_id").Include("Car"))
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent. I get an error says Missing ')' on SetFields function. Do you get an error?
add MongoDB.Driver.Builders. before Fileds and see what happens
Same result. Is this driver for powershell 3.0+ ? I am using 2.0
-1

Try this:

$results = $collection.Find($query).SetFields( [MongoDB.Driver.Builders.fields]::Exclude("_id").include("Car"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.