How to make comlex query MongoDB with Powershell

2019-04-01 18:49发布

问题:

I need to retrieve data from mongoDB using Powershell. Let's say I have db.orders collection and need to retrieve only orders created during last week and retrieve only specific columns for instance _id, status, createdAt fields.

Orders collection schema

{
 "_id": ObjectId("56cf9bab78e9fd46ec557d69"),
 "status" : "ordered",
  ...
 "total": 343,
 "createdAt": ISODate("2016-01-15T17:29:09.342Z")
}

I can query it in mongo shell like this

db.orders.find({ 
  "createdAt" : { 
    $lt: new Date(), 
    $gte: new Date(new Date().setDate(new Date().getDate()-7))
  }   
}, {_id: 1, status: 1, createdAt: 1 })

But I need to do it in Powershell, here is my Powershell script with simple query which extract exactly createdAt date.. not range of dates

$mongoDbDriverPath = "C:\mongodb\bin"
$dbName = "Orders"
$collectionName = "orders"
Add-Type -Path "$($mongoDbDriverPath)\MongoDB.Bson.dll"
Add-Type -Path "$($mongoDbDriverPath)\MongoDB.Driver.dll"
$db =[MongoDB.Driver.MongoDatabase]::Create("mongodb://localhost:27017/$($dbName)")
$collection = $db[$collectionName]

$query = [MongoDB.Driver.Builders.Query]::EQ("createdAt","2016-01-15T17:29:09.342Z")

$results = $collection.find($query)

In MongoDB .NET Driver api, I can't make complex query or at least don't know how. I can query according to one specific column, but not making complex one and can't limit output for some fields.

Please advise if anyone knows how to. Note: it's not a .Net project, it just uses mongoDB .net driver, but executed in Powershell.

回答1:

please find solution below: It is a flexible code using c# inside powershell script and latest mongo drivers (2.2.3) - so you can play with c# code as required :-)

$mongoDbDriverPath = "C:\work\mongo"
$dbName = "deser"
$collectionName = "Foo"
$Assem = ( "$($mongoDbDriverPath)\MongoDB.Bson.dll", "$($mongoDbDriverPath)\MongoDB.Driver.dll","$($mongoDbDriverPath)\MongoDB.Driver.Core.dll") 

$Source = @” 
namespace profesor79
{
    using System.Collections.Generic;

    using MongoDB.Bson;
    using MongoDB.Bson.Serialization.Attributes;
    using MongoDB.Driver;

    public static class Executor
    {
        public static List<Foo> GetData()
        {
            var connectionString = "mongodb://localhost:27017";
            var _client = new MongoClient(connectionString);
            var _database = _client.GetDatabase("deser");
            var cole = _database.GetCollection<Foo>("Foo");
            cole.InsertOne(new Foo());

            var data = cole.Find<Foo>((new BsonDocument())).ToList();
            return data;
        }

        public class Foo
        {
            public ObjectId Id { get; set; }
            [BsonDictionaryOptions]
            public Dictionary<string, string> Bar = new Dictionary<string, string>() { { "1", "text" }, { "2", "text" } };

        }
    }
}


"@

Add-Type  -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp  

[profesor79.Executor]::GetData()

see screenshot: